ios - 使用扩展来扩展多个类

标签 ios swift uitableview swift-protocols swift-extensions

我正在使用如下所示的 TableView 数据源扩展。我想将此扩展应用于我的应用程序中的多个 tableview Controller 。我看不到任何简单的方法来允许单个通用扩展扩展多个类,而无需将相同的代码复制并粘贴到不同的单独扩展中。可能的解决方案是定义一个 protocol相反,然后扩展协议(protocol)。然而在那些情况下,它们在协议(protocol)中定义然后扩展的函数是自定义函数,而在 TableView 数据源扩展中我想应用于许多类,这些函数是覆盖标准 TableView 数据源方法的功能。我可以使用此模式通过此代码扩展多个类还是有其他解决方案。

extension PopularTableViewController
{
    // MARK: UITableViewDataSource

    override func numberOfSections(in tableView: UITableView) -> Int {
        return fetchedResultsController?.sections?.count ?? 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let sections = fetchedResultsController?.sections, sections.count > 0 {
            return sections[section].numberOfObjects
        } else {
            return 0
        }
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if let sections = fetchedResultsController?.sections, sections.count > 0 {
            return sections[section].name
        } else {
            return nil
        }
    }

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return fetchedResultsController?.sectionIndexTitles
    }

    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return fetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
    }
}

最佳答案

您可以创建 UITableViewController 的子类,将扩展添加到您的子类,然后让您想要的所有其他 TableView Controller 继承您创建的子类。

关于ios - 使用扩展来扩展多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45702579/

相关文章:

ios - 由于 Xcode 错误导致的 pod 规范 lint 验证错误

ios - 如何从 View 获取数据到 UITabBarController

ios - 在 iPad 中显示矢量 map

iOS Swift float 操作按钮在更改屏幕时移动

swift - 字典导致 Swift 中索引超出范围错误

ios - 在 iOS 中使用 Swift 更改 UIAlertAction 的 UIAlertController 按钮标题的字体大小

ios - Swift Spritekit 等距 map 触摸位置

ios - 从 C api 接收多维数组,如何在 Swift 中处理?

ios - 在编辑模式下更改 UITableViewCell 中红色减号按钮的位置

iphone - 将 iPhone 上分组 UITableView 中的选择数量限制为每组一个单元格/行