我想在我的UITableView
添加一些自定义部分标题,我在网上搜索并看到很多人正在创建一个UITableViewCell
子类并将其注册为标题,这听起来像一个不好的做法,因为有一个特定的页眉和页脚类称为UITableViewHeaderFooterView
。
所以我试着自己做,我已经创建了一个xib文件和一个UITableViewHeaderFooterView
子类 - 称为SelectedProductsSectionHeader
。
这是UITableViewController方面的相关代码 -
override func viewDidLoad() {
super.viewDidLoad()
let selectedProductsSectionHeaderNib = UINib(nibName: "SelectedProductsSectionHeader", bundle: nil)
tableView.register(selectedProductsSectionHeaderNib, forHeaderFooterViewReuseIdentifier: "selectedProductsHeader")
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == SectionIndex.selectedProducts{
let selectedProductsHeaderCell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "selectedProductsHeader") // throws error
guard let selectedProductsHeader = selectedProductsHeaderCell as? SelectedProductsSectionHeader else { return nil }
return selectedProductsHeader
}
return nil
}
运行时错误:
由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[setValue:forUndefinedKey:]:此类不是密钥标签的密钥值编码兼容。
所以我尝试了其他的东西,而不是将File的所有者设置为我的自定义类,我将View设置为我的自定义类,并且它有效。
这是一个很好的问题。在视图本身上设置类时它不起作用的原因是它没有一个子视图。每当您想要将根视图作为子类时,您需要再添加一个容器视图,因为加载的nib需要父视图。
您需要做的就是将类设置为根视图,在容器视图中拖动并将其约束到superview的所有边,然后添加子视图,它将起作用。