【发布时间】:2016-03-17 02:18:56
【问题描述】:
我正在努力实现使我的 uilabel 从左侧延伸到右侧(全宽),我可以在情节提要中轻松做到这一点,但我的应用程序中有一部分需要以编程方式显示 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)
这是我的截图:
【问题讨论】:
-
你需要使用AutoLayout,使用NSLayoutConstraint或者第三方Masonry或者SnapKit
-
如果您必须以编程方式进行,那么视觉格式语言将是您的最佳选择。这是一个教程raywenderlich.com/110393/…
-
如果您将 UILabel 放在另一个 UIView 中,将全宽度约束添加到该 UIView,将其背景颜色设置为您需要的颜色,则可能会发生您想要达到的效果。然后在该视图中添加 UILabel 并再次使用约束将其居中在该 UIView 中。目前您的 UILabel 的背景是灰色的,它不会拉伸,因为它是文本的大小
标签: ios swift uilabel nslayoutconstraint ios-autolayout