viewForHeaderInSection宽度不正确

我的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(或类似的东西),因为我有部分隐藏的行。 在我看来,我必须增加“查看”一些约束编程,但我不知道如何

定义一个customView: UITableViewHeaderFooterView类,并在viewDidLoad: View Controller中写入

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

而不是出队一个单元,出队一个UITableViewHeaderFooterView (因为这是正确的方式)。

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

你应该使用相同的tableview和height的宽度来定义你所需要的headerview 。 不要给细胞的高度或宽度。 如果你使用的是UI的storyborard,然后在上面的tableview上拖动uiview它会自动设置为headerview,然后给top,leading,trailing and fix heigth constraints viewForHeaderInSection top,leading,trailing and fix heigth constraints并删除viewForHeaderInSection方法。

希望这会帮助:)