ios - 带有 uitableviewdatasource 的快速协议(protocol)

标签 ios swift

<分区>

我想重用下面的代码

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 3
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return UITableViewCell()
}

我定义一个协议(protocol):

protocol ConfigDetail: class, UITableViewDataSource{}

extension ConfigDetail{

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 3
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return UITableViewCell()
}

}

但是当我将协议(protocol)与 UIViewController 一起使用时,它总是告诉我我不符合协议(protocol) UITableViewDataSource,或者我必须在我的协议(protocol)之前添加 @objc。但是我在协议(protocol)中定义了结构变量,@objc 可能无济于事。有什么解决办法吗?

最佳答案

如果要实现这些数据源方法并重用它们,只需定义一个实现它们的数据源类即可。然后不在 View Controller 中实现委托(delegate)方法,而是实例化一个数据源对象,保持对它的强引用,并将其指定为 TableView 的数据源。

例如:

class DataSource: NSObject, UITableViewDataSource {

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 3
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
        // configure cell here
        return cell
    }
}

class ViewController: UITableViewController {

    let dataSource = DataSource()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = dataSource
    }

}

关于ios - 带有 uitableviewdatasource 的快速协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37522318/

相关文章:

ios - UITapGestureRecognizer 在第一个选项卡中不起作用

ios - 从 Collection View 中删除项目

ios - 在 swift 中解析 Json 后获取空数据

ios - 集中管理身份验证的方式

swift - 除了帮助 iOS 中的特征收集外,UIPresentationController 还需要什么?

objective-c - 在 Objective-C 和 iOS 中,似乎委托(delegate)可以去任何方向?

jquery - backbone.js 路由器在 PhoneGap iOS 构建中失败

Swift DiffableDataSource 进行插入和删除而不是重新加载

ios - 来自 CloudKit 的推送通知未正确同步

swift - 无法访问闭包之外的自定义