ios - 将 UILabel 在 UITableView header 中居中

标签 ios swift uitableview nslayoutconstraint

我将我的 UIView 添加为 UITableView header ,但是当我这样做时,我的约束就崩溃了。我试图让我的 chapterVerseLabel 像这样在圆圈内居中:

enter image description here

到目前为止,我通过这样做完成了这个:

    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)

但这是结果:

enter image description here

现在,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/

相关文章:

ios - 如何将 Magicalvoxel 文件导入 Xcode 并使用它

iphone - 代表 uitableview 中的必填字段

ios - cellForRowAtIndexPath 没有被调用?

ios - 火力基地 |远程通知不显示,swift 3.0

iphone - beginBackgroundTaskWithExpirationHandler 永远不会被调用

ios - iOS 7.1 是否打破了非报亭应用程序的内容可用(又名无声)推送通知?

ios - 在 stackview swift ios 中隐藏其他小部件时,文本字段会放大

ios - 如何将文本叠加在正在播放到 Apple TV 的 DRM 视频上?

ios - 如何像UITableview数据源一样返回 View 数(ZLSwipeableViewSwif)?

ios - 谷歌登出