ios - 使 UILabel 约束显示全宽

标签 ios swift uilabel nslayoutconstraint ios-autolayout

我正在努力实现让我的 uilabel 从左侧拉伸(stretch)到右侧(全宽),我可以在 Storyboard中轻松完成,但我的应用程序中有一部分需要以编程方式显示 uilabel。 这是我的代码:

textLabel.backgroundColor = UIColor.grayColor()
textLabel.text = StringsLabel.NOINTERNET
textLabel.textAlignment = .Center
textLabel.font = UIFont.boldSystemFontOfSize(24.0)
textLabel.translatesAutoresizingMaskIntoConstraints = false
centerView.addSubview(textLabel)

let centreXTopLabel:NSLayoutConstraint = NSLayoutConstraint(item: textLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: centerView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0);
        centerView.addConstraint(centreXTopLabel)

这是我得到的截图:

enter image description here

最佳答案

在 0 点将其固定到 View 的前导和尾随:

let leading = NSLayoutConstraint(item: textLabel, attribute: .Leading, relatedBy: .Equal, toItem: centerView, attribute: .Leading, multiplier: 1, constant: 0)
let trailing = NSLayoutConstraint(item: textLabel, attribute: .Trailing, relatedBy: .Equal, toItem: centerView, attribute: .Trailing, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([leading, trailing])

请注意,这将导致布局不明确——您需要添加一个垂直定位标签的约束。

关于ios - 使 UILabel 约束显示全宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36050518/

相关文章:

ios - FBSOpenApplicationErrorDomain 代码 =4 错误

ios - MessageComposeViewController 仅出现一次

ios - 自定义 UITableViewCells 以及正确使用prepareForReuse和removeFromSuperview

ios - 如何在 Storyboard中添加自定义 UIControl 类?

ios - 单点触控中 UILabel 中的文本下划线(移植 ObjC 代码)

ios - Swift 中的自动换行标签

ios - 滚动时SwiftUI NavigationBar不会消失

ios - 奇怪的将 NSString 转换为 int 问题

ios - 执行 segue 时隐藏键盘转换

iphone - 如何为 UILabel 的文本而不是背景添加渐变?