在 UITableView 中居中 UILabel Header

Centering a UILabel inside of a UITableView Header

我将我的 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

有什么想法吗?

中间有一个uiview。如果你想在中心的圆形视图中添加一个视图(1/4),你不能用视觉格式来做。我假设你想居中 chapterVerseLabel。 所以:

chapterVerseLabel.translatesAutoresizingMaskIntoConstraints = false
yourCircularView.addsubView(chapterVerseLabel)
let xCenterConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterX, relatedBy: .Equal, toItem: view2, attribute: .CenterX, multiplier: 1, constant: 0)
superview.addConstraint(xCenterConstraint)

let yCenterConstraint = NSLayoutConstraint(item: chapterVerseLabel, attribute: .CenterY, relatedBy: .Equal, toItem: view2, attribute: .CenterY, multiplier: 1, constant: 0)
superview.addConstraint(yCenterConstraint)

你的约束的问题是你已经通过给出顶部和底部约束来限制标签​​。我也没有看到前导和尾随约束你实际上必须根据你的要求垂直或水平或同时对齐标签。

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 是您的 header 视图,它从 headerforView 委托方法返回。您需要为标签提供高度和宽度。