I'm trying to get the Visual Format Language working in swift but I just can't get it to work with a simple example. I'm trying to get the label to show up somewhere else other than the top left corner. This is how it shows up now:
And this is my code:
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
label.text = "Label 1"
label.sizeToFit()
self.view.addSubview(label)
self.view.translatesAutoresizingMaskIntoConstraints = false
let views = Dictionary(dictionaryLiteral: ("label", label))
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-30-[label]-|",
options: [],
metrics: nil,
views: views)
self.view.addConstraints(horizontalConstraints)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-30-[label]-|",
options: [],
metrics: nil,
views: views)
self.view.addConstraints(verticalConstraints)
}
Can anyone see what is wrong?
You need to add label.translatesAutoresizingMaskIntoConstraints = false
Without this, the label's autoresizing mask is transformed into constraints when layoutSubviews
is performed. The boolean applies only to the view and not its subviews.