我正在使用如下所示的 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/