首页 > 解决方案 > 如何在 Objective-C 项目中遵循 Swift 库中的协议

问题描述

我必须在 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

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

一个objective-c类可以符合一个swift协议吗?

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

标签: iosobjective-cswift

解决方案


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


推荐阅读