Swift:以编程方式向UILabel添加约束

时间:2016-05-17 12:47:00

标签: swift autolayout uilabel ios-autolayout

所以我从iOS开发中休息了4个月,似乎我已经忘记了一切。我想要做的就是以编程方式将标签放置在0,0,大小为200,50。我听说iOS8中有一些我不记得的变化

let x : CGFloat = 0.0
let y : CGFloat = 0.0
let width : CGFloat = 200.0
let height : CGFloat = 50.0
self.label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
self.label.text = "SIMON"
self.label.textColor = UIColor.whiteColor()

self.label.font = UIFont(name: "HelveticaNeue-UltraLight", size: 24)
self.label.textAlignment = NSTextAlignment.Center
self.label.backgroundColor = UIColor.redColor()
self.label.layer.masksToBounds = true;
self.label.layer.cornerRadius = 8.0;
self.label.adjustsFontSizeToFitWidth = true;

self.label.translatesAutoresizingMaskIntoConstraints = false

widthConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: width)

heightConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: height)

leftConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: x)

topConstraint = NSLayoutConstraint(item: self.label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: y)

self.view.addSubview(self.label)

NSLayoutConstraint.activateConstraints([leftConstraint,topConstraint, widthConstraint, heightConstraint] )

1 个答案:

答案 0 :(得分:0)

看来我正在转储!

这是我从中调用它的事件,而不是代码。已移至viewWillAppear