繁体   English   中英

如何使类符合Swift中的协议?

[英]How to make a class conform to a protocol in Swift?

在Objective-C中:

@interface CustomDataSource : NSObject <UITableViewDataSource>

@end

在斯威夫特:

class CustomDataSource : UITableViewDataSource {

}

但是,将出现一条错误消息:

  1. 类型'CellDatasDataSource'不符合协议'NSObjectProtocol'
  2. 类型'CellDatasDataSource'不符合协议'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
    }
}

Xcode 9有助于实现Swift数据源和代理的所有必需方法。

这是UITableViewDataSource示例:

显示警告/提示以实现强制方法:

在此输入图像描述

单击“修复”按钮,它将在代码中添加所有必需的方法:

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM