![](/img/trans.png)
[英]How to make an Objective-C class conform to a protocol defined in Swift?
[英]How to make a class conform to a protocol in Swift?
在Objective-C中:
@interface CustomDataSource : NSObject <UITableViewDataSource>
@end
在斯威夫特:
class CustomDataSource : UITableViewDataSource {
}
但是,将出现一条错误消息:
什么应该是正确的方法?
类型'CellDatasDataSource'不符合协议'NSObjectProtocol'
您必须使您的类继承自NSObject
以符合NSObjectProtocol
。 Vanilla Swift课程没有。 但是UIKit
许多部分都期望NSObject
。
class CustomDataSource : NSObject, UITableViewDataSource {
}
但是这个:
类型'CellDatasDataSource'不符合协议'UITableViewDataSource'
是期待。 在您的类实现协议的所有必需方法之前,您将收到错误。
所以得到编码:)
在遵循协议之前,类必须从父类继承。 这主要有两种方法。
一种方法是让您的类继承自NSObject
并一起符合UITableViewDataSource
。 现在,如果要修改协议中的函数,则需要在函数调用之前添加关键字override
,如下所示
class CustomDataSource : NSObject, UITableViewDataSource {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
}
但是,这有时会使您的代码变得混乱,因为您可能需要遵循许多协议,并且每个协议可能具有多个委托功能。 在这种情况下,您可以使用extension
名将符合协议的代码与主类分开,并且您不需要在扩展中添加override
关键字。 所以相当于上面的代码
class CustomDataSource : NSObject{
// Configure the object...
}
extension CustomDataSource: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.