viewForHeaderInSection 不正确的宽度

viewForHeaderInSection incorrect width

我的 headerView 的宽度不适应屏幕的宽度。 我的 viewForHeaderInSection 函数:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("sectionCell") as! sectionCell
    cell.hint.text = "some name"

    cell.tag = section


    let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapOnSection(_:)))

    cell.addGestureRecognizer(singleTap)

    let view = UIView(frame: cell.frame)

    view.addConstraints(cell.constraints)

    view.addSubview(cell)

    return view
}

我必须将单元格添加到 UIView(或类似的东西),因为我在该部分中隐藏了行。 在我看来,我必须以编程方式向 "view" 添加一些约束,但我不知道如何

您应该将 headerview 定义为与 tableview 相同的宽度和您要求的 ui 高度。不要给出单元格的高度或宽度。如果你正在为 ui 使用 storyborard,然后将 uiview 拖到上方的 tableview 上,它会自动设置为 headerview 然后给出 top,leading,trailing and fix heigth constraints 并删除 viewForHeaderInSection 方法。

希望这会有所帮助:)

定义一个customView: UITableViewHeaderFooterViewclass,然后在View Controller的viewDidLoad:中写入

tableView.registerClass(customView.classForCoder(), forHeaderFooterViewReuseIdentifier: "HeaderIdentifier")

而不是将单元格出列,而是将 UITableViewHeaderFooterView 出列(因为这是正确的方法)。

这样你必须在代码中添加自动布局或在 nib 文件中定义它,使用 nib 并处理各种事情有点令人沮丧,如果你使用这种方法我建议使用这个库 NibDesignable.