简体   繁体   English

使UILabel约束显示全宽

[英]Make UILabel Constraint to display full width

I'm struggling to implement to make my uilabel to stretch from the left side to right side (Full Width), I can do it easily in storyboard but I have a part on my app that needs to display a uilabel progmatically. 我正在努力实现使uilabel从左侧延伸到右侧(全宽)的工作,我可以在情节提要中轻松实现,但是我的应用程序中有一部分需要以编程方式显示uilabel。 Here's my code: 这是我的代码:

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)

Here's the screenshot of what i've got: 这是我所拥有的屏幕截图:

在此处输入图片说明

Pin it to the leading and trailing of the view at 0 points: 在0点将其固定到视图的开头和结尾:

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])

Note that this will result in an ambiguous layout — you need to add a constraint that positions the label vertically. 请注意,这将导致布局不明确-您需要添加一个约束来垂直放置标签。

Try this.. 尝试这个..

let views = ["textLabel" : textLabel]
let formatString = "|-[textLabel]-|"

 let constraints = NSLayoutConstraint.constraintsWithVisualFormat(formatString, options:.AlignAllTop , metrics: nil, views: views)

NSLayoutConstraint.activateConstraints(constraints)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM