gpt4 book ai didi

ios - 在两个不同的类中实现 UITableViewDataSource 协议(protocol)

转载 作者:搜寻专家 更新时间:2023-10-30 22:11:14 25 4
gpt4 key购买 nike

我不确定是否可以这样做,或者是否不推荐这样做。

我想要实现的是以下内容:

我有 2 个类 classAclassB,它们引用了相同的 UITableview 实例。我想要的是 classA 负责 UITableViewDataSource 协议(protocol)的 2 个必需方法的实现:

  • numberOfRowsInSection
  • cellForRowAt

然后我希望 classB 能够实现其他可选方法,例如 titleForHeaderInSection

那么 classA 如何拥有一些协议(protocol)方法的默认实现,并让 classB 成为一个可以构建在 classB 之上的类> 完成了吗?

在某种程度上,我面临的问题如下:多个类如何成为单个 UITableView 的数据源?

编辑:classA 将在我正在编写的库中,该库负责构建 tableView 的核心部分。 classB 将由第 3 方开发人员使用,主要用于自定义其外观。

最佳答案

我认为唯一无需手动重定向所有内容的解决方案是使用协议(protocol)方法的默认实现,例如:

protocol MyTableViewProtocol : UITableViewDelegate, UITableViewDataSource {

}

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

然后让 ClassB 实现 MyTableViewProtocol 而不是 UITableViewDelegateUITableViewDataSource

但是,这样的解决方案不会起作用,因为 Obj-C 无法访问协议(protocol)扩展。

我认为一个更干净(和有效)的解决方案是在协议(protocol)之外创建 numberOfRowsInSectioncellForRowAt 的实现,只让 ClassB在委托(delegate)方法中调用它们,例如:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return MyTable.tableView(tableView: tableView, numberOfRowsInSection: section)
}

这样的解决方案对用户来说会更清晰,因为它包含的“魔法”更少。

当然,经典的解决方案是定义自己的委托(delegate):

protocol MyTableViewProtocol {
func myTableView(_ tableView: MyTableView, ...)
...
}

并从您的委托(delegate)中将所有内容重定向到它。

此解决方案使 ClassB 无法覆盖您不希望它覆盖的委托(delegate)函数。

关于ios - 在两个不同的类中实现 UITableViewDataSource 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42164379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com