我可以像下面这样以编程方式创建简单的自定义 viewForHeaderInSection。但我想做更复杂的事情,可能与不同的类连接并像 tableView 单元格一样访问它们的属性。很简单,我想看看我在做什么。
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if(section == 0) {
let view = UIView() // The width will be the same as the cell, and the height should be set in tableView:heightForRowAtIndexPath:
let label = UILabel()
let button = UIButton(type: UIButtonType.System)
label.text="My Details"
button.setTitle("Test Title", forState: .Normal)
// button.addTarget(self, action: Selector("visibleRow:"), forControlEvents:.TouchUpInside)
view.addSubview(label)
view.addSubview(button)
label.translatesAutoresizingMaskIntoConstraints = false
button.translatesAutoresizingMaskIntoConstraints = false
let views = ["label": label, "button": button, "view": view]
let horizontallayoutContraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[label]-60-[button]-10-|", options: .AlignAllCenterY, metrics: nil, views: views)
view.addConstraints(horizontallayoutContraints)
let verticalLayoutContraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0)
view.addConstraint(verticalLayoutContraint)
return view
}
return nil
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
有没有人解释一下如何使用 xib 创建自定义 tableView 标题视图?我遇到过旧的 Obj-C 主题,但我对 Swift 语言很陌生。如果有人解释得这么详细,那就太好了。
1.issue:按钮 @IBAction 未与我的 ViewController 连接。(Fixed)
使用文件所有者、ViewController 基类解决(单击左侧大纲菜单。)
2.issue:表头高度问题(Fixed)
解决添加headerView.clipsToBounds = true in viewForHeaderInSection: 方法。
对于约束警告 这个答案解决了我的问题 https://stackoverflow.com/questions/11664115/unable-to-simultaneously-satisfy-constraints-will-attempt-to-recover-by-breakin/30096600#30096600:
当我在 viewController 中使用此方法添加 ImageView 甚至相同的高度约束时,它会流过 tableView 行看起来像图片 https://i.stack.imgur.com/yoYQ6.png.
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 120
}
如果我使用viewDidLoad中的automaticallyAdjustsScrollViewInsets,在这种情况下图像会在navigationBar下流动。 -固定的-
self.automaticallyAdjustsScrollViewInsets = false
3.issue:“查看”下的“如果”按钮(Fixed)
@IBAction func didTapButton(sender: AnyObject) {
print("tapped")
if let upView = sender.superview {
if let headerView = upView?.superview as? CustomHeader {
print("in section \(headerView.sectionNumber)")
}
}
}