繁体   English   中英

UITableView 自定义部分标题

[英]UITableView Custom Section Header

我想在我的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's Owner 设置为我的自定义类,而是将 View 设置为我的自定义类,并且它起作用了。

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

我的问题是为什么第一种方法不起作用? 我应该使用文件所有者吗? 如果不是-我应该如何使用它?

这是一个很好的问题。 当您在视图本身上设置类时它不起作用的原因是它没有一个子视图。 每当你想让根视图成为一个子类时,你需要再添加一个容器视图,因为加载的 nib 需要一个父视图。

您需要做的就是将类设置为根视图,拖入容器视图并将其约束到父视图的所有边缘,然后添加您的子视图,它就会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM