ios - 如何在 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
根据前面的问题,显然我不能在我的头文件中使用这个协议。
所以我想知道如何使用这个协议,以便在我的 ViewController.m 中符合它并在我的 tableview 中具有骨架效果。
解决方案
简短的回答是你不能。如果您使用该属性,Swift 可以生成与 Objective C 兼容的 thunk @objc
,但是当 Swift 知道 Objective C 时,Objective C 不知道 Swift。你可以通过编写一个符合你的协议的 Swift ViewController 来解决这个问题,然后将整个类标记为objc
. 这样,您的目标 C 类可以覆盖所有实际实现 Swift 协议的方法,而无需真正了解 Swift 协议。
推荐阅读
- c++ - 用 static_cast<>() 声明变量时使用 auto 的目的是什么?
- javascript - javascript中的Postgres RegExp验证
- azure-service-fabric - 缺少群集证书会导致 Add-AzServiceFabricClusterCertificate 失败:对象引用未设置为对象的实例
- php - 使用 PHP 邮件时提交 HTML 表单时出现 HTTP ERROR 405
- python - 在while循环python中创建简单列表
- c# - 是否可以从 Visual Studio 内部构建主要的 Unity C# 项目?
- json - 在 React Js 中使用地图访问嵌套 json
- javascript - 解决 forEach 不是函数
- php - PHP SELECT/Show last[number] 插入数据库的项目
- django - Python reportlab - 如何在 SimpleDocTemplate 的最后一页上绘制一些东西?