gpt4 book ai didi

ios - 为覆盖 ViewController 方法提供默认实现,但前提是 Controller 符合协议(protocol)

转载 作者:行者123 更新时间:2023-11-28 12:32:44 25 4
gpt4 key购买 nike

在我的应用程序中,只要某个 Controller 中有 UITableView,我就必须编写大量样板代码。为了消除它,我创建了一个 BaseTableViewController,它实现了一些重复使用的 UITableDataSource 操作,例如 tableView(_:numberOfRowsInSection:)tableView( _:cellForRowAt:)。在 tableView(_:numberOfRowsInSection:) 中,我的 BaseTableViewController 从另一个方法(我们称之为 rowCount(inSection:))检索一个部分中的实际行数并执行一些使用它进行计算,然后将结果返回给委托(delegate)调用者。 BaseTableViewController 的每个子类都必须覆盖 rowCount(inSection:) 方法并在给定部分返回其正确的行数(BaseTableViewController 本身在其默认实现中返回 0)。

现在,我的一些 TableView Controller 支持显示记录的分页 - 当用户将 TableView 滚动到最后一行时,下一批行将从网络中检索。为了使事情更加面向协议(protocol),我为可分页 Controller 创建了一个协议(protocol):

protocol Pageable: class {
associatedtype DataType
var pages: [[DataType]] { get set } // Each page is an array of elements, hence the table in a table
func loadNextPage()
}

如果 Controller 是Pageable,则rowCount(inSection:) 方法总是如下所示:

override func rowCount(inSection: Int) -> Int {
return self.pages[section].count
}

这很乏味,因为每个也是 Pageable 的 BaseTableViewController 后代都必须有这个确切的实现,这违反了 DRY。

我无法在 Pageable 的协议(protocol)扩展中添加默认实现,因为该 Controller 已经具有从 BaseTableViewController 继承的自己的实现。

我想出了一个解决方案,但我不喜欢它:我可以创建一个 PageableTableViewController(BaseTableViewController 的子类),它提供自己的 rowCount(inSection:) 重写实现,但是这不是很面向协议(protocol)的。我还尝试将 rowCount(inSection:) 方法移动到一个协议(protocol)中,但是如果我让 BaseTableViewController 的所有后代都符合具有协议(protocol)扩展的协议(protocol),扩展 Pageable实现该方法将不起作用。

我将如何创建一种机制,使 BaseTableViewController 的所有子类都能够覆盖 rowCount(inSection:) 方法,但是当它们是 Pageable 时,他们共享它的默认实现(可能)放置在 Pageable 协议(protocol)扩展中?

最佳答案

您可以通过协议(protocol)扩展实现您想要的。如果实现协议(protocol)的对象实际上是 UIViewController,则扩展将适用。

protocol something {
func method()
}
extension something where Self: UIViewController {
func method() {
//Default implementation
}
}

关于ios - 为覆盖 ViewController 方法提供默认实现,但前提是 Controller 符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41678322/

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