我可以通过编程方式创建简单的自定义viewForHeaderInSection,就像下面这样。但是我希望能做更复杂的事情,比如与不同的类连接并访问它们的属性,就像tableView cell一样。简单地说,我想看看我所做的。
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.问题: Button @IBAction无法连接到我的ViewController。(已修复)
通过File's Owner、ViewController基类 (点击左侧大纲菜单)解决了问题。
2.问题: 头部高度问题(已修正)
在viewForHeaderInSection:方法中添加headerView.clipsToBounds = true即可解决问题。
对于约束警告,这个答案解决了我的问题:
当我在viewController中使用这种方法添加ImageView时,即使与同样高的约束条件相同,它也会覆盖tableView行,看起来像图片。
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 120
}
如果我在viewDidLoad中使用automaticallyAdjustsScrollViewInsets,在这种情况下,图片会流动到导航栏下面。-已修复-
self.automaticallyAdjustsScrollViewInsets = false
问题3: 如果按钮在“查看”下面(已修复)
@IBAction func didTapButton(sender: AnyObject) {
print("tapped")
if let upView = sender.superview {
if let headerView = upView?.superview as? CustomHeader {
print("in section \(headerView.sectionNumber)")
}
}
}