【问题标题】:How to conform a protocol made in a Swift library in a Objective-C project如何在 Objective-C 项目中遵循 Swift 库中的协议
【发布时间】:2019-12-20 18:23:43
【问题描述】:

我必须在 Objective-C 项目中实现骨架效果。我在 Objc 上找到了很多库,但它们没有执行我想做的事情。我找到了这个 Swift 库——https://github.com/Juanpe/SkeletonView。 我使用带有此扩展的桥接头使其与任何 UIView 一起使用。

快速文件


extension UIView {
    @objc public func showWaitingLoader() {
        let gradient = SkeletonGradient(baseColor: UIColor(red:0.9, green:0.9, blue:0.9, alpha:1))
        let animation = SkeletonAnimationBuilder().makeSlidingAnimation(withDirection: GradientDirection.leftRight)
        self.showAnimatedGradientSkeleton(usingGradient: gradient, animation: animation)
    }

    @objc public func hideWaitingLoader(){
        self.hideSkeleton(reloadDataAfter: true)
    }
}

Objective-C 文件

#import "ViewController.h"
#import "SkeletonView-Swift.h"
#import "Skeleton-Swift.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *firstLabel;
@property (weak, nonatomic) IBOutlet UIView *container;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

- (void)viewDidLoad {
    [super viewDidLoad];
    _firstLabel.isSkeletonable = YES;
    [_container showWaitingLoader];
}

效果非常好。但是现在我需要一个集合(TableView)中的这个效果。该库说要使视图控制器符合下一个协议,即下一个。

public protocol SkeletonTableViewDataSource: UITableViewDataSource {
    func numSections(in collectionSkeletonView: UITableView) -> Int
    func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int
    func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier
}

但我不知道如何在我的头文件(Objective-C 项目)上使用此协议。像这样

#import <UIKit/UIKit.h>
#import "SkeletonView-Swift.h"
#import "Skeleton-Swift.h"
@interface ViewController : UIViewController <SkeletonTableViewDataSource>

@end

根据上一个问题,显然我不能在我的头文件中使用这个协议。

Can an objective-c class conform to a swift protocol?

所以我想知道如何使用这个协议,以便在我的 ViewController.m 中符合它并在我的 tableview 中具有骨架效果。

【问题讨论】:

  • 您必须使用@protocol 声明。
  • 你介意提供一个例子吗:D?

标签: ios objective-c swift


【解决方案1】:

简短的回答是你不能。如果您使用 @objc 属性,Swift 可以生成与 Objective C 兼容的 thunk,但是当 Swift 知道 Objective C 时,Objective C 不知道 Swift。你可以通过编写一个符合你的协议的 Swift ViewController 来解决这个问题,然后将整个类标记为objc。这样,您的目标 C 类可以覆盖所有实际实现 Swift 协议的方法,而无需真正了解 Swift 协议。

【讨论】:

  • 哇,谢谢你的解释。幸运的是,我在 Swift 中找到了一个支持 Objc 的库,最后我可以实现骨架效果。我会将这个答案标记为已接受,因为它帮助我理解了 iOS 中更好的互操作性。谢谢你:D。我要使用的库是github.com/malkouz/ListPlaceholder,以防有人希望在他们的 objc 项目中使用这种效果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 2015-01-01
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多