我将我的 UIView 添加为 UITableView header ,但是当我这样做时,我的约束就崩溃了。我试图让我的 chapterVerseLabel
像这样在圆圈内居中:
到目前为止,我通过这样做完成了这个:
var allConstraints = [NSLayoutConstraint]()
let views = ["tableView" : tableView, "containerView" : containerView, "chapterVerseLabel" : chapterVerseLabel]
allConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-70-[chapterVerseLabel]-70-|", options: [], metrics: nil, views: views)
NSLayoutConstraint.activateConstraints(allConstraints)
但我也不确定如何让它居中。似乎我所有的尝试都将它居中,不遵守在 UITableView header 中居中某些内容的更严格规则。
欢迎所有想法。
更新
我尝试添加一个 .CenterX 值:
let leftConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
containerView.addConstraint(leftConstraint)
let rightConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterX, relatedBy: .Equal, toItem: containerView, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
containerView.addConstraint(rightConstraint)
但这是结果:
现在,chapterVerseLabel 位于我的 containerView 中,它被指定为 tableView.tableHeaderView
。像这样:
tableView.tableHeaderView = containerView
有什么想法吗?
最佳答案
您的约束的问题是您已经通过给出顶部和底部约束来限制标签。我也没有看到前导和尾随约束你实际上必须根据你的要求垂直或水平或同时对齐标签。
NSLayoutConstraint *yCS =[NSLayoutConstraint constraintWithItem:chapterVerseLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
[containerView addConstraint:yCS];
NSLayoutConstraint *xCS =[NSLayoutConstraint constraintWithItem:chapterVerseLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
[containerView addConstraint:xCS];
假设 containerView 是您的标题 View ,它从 headerforView 委托(delegate)方法返回。您需要为标签提供高度和宽度。
关于ios - 将 UILabel 在 UITableView header 中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36206094/