Frederick C. Lee
Frederick C. Lee

Reputation: 9513

NSLayoutConstraints: How do you correctly center a subview within a view?

Greeting:

I'm trying to center a UILabel '1' inside a green button.

enter image description here

Here's my code:

let dayFrame = CGRectMake(1, 1, 16, 16)
let myLabel1 = UILabel(frame:dayFrame)
myLabel1.font = calFont

myLabel1.tag = 100
dayButton1.addSubview(myLabel1)

var viewDictionary:Dictionary = ["myLabel": myLabel1]

dayButton1.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
    "H:|[myLabel]|",
    options:nil, metrics:nil,
    views:viewDictionary))
dayButton1.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
    "V:|[myLabel]|",
     options:nil, metrics:nil,
     views:viewDictionary))

However I got the following runtime error:

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSIBPrototypingLayoutConstraint:0x7fbebae37010 'IB auto generated at build time for view with fixed frame' H:[UIButton:0x7fbebae47ac0(28)]>",
    "<NSLayoutConstraint:0x7fbebacb5fc0 H:|-(0)-[UILabel:0x7fbebae9aa00'1']   (Names: '|':UIButton:0x7fbebae47ac0 )>",
    "<NSLayoutConstraint:0x7fbebacd68a0 H:[UILabel:0x7fbebae9aa00'1']-(0)-|   (Names: '|':UIButton:0x7fbebae47ac0 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x7fbebc421b70 h=--& v=--& UILabel:0x7fbebae9aa00'1'.midX == + 9>"
)

I'm not sure what I'm doing wrong. I merely added a Vertical & Horizontal constraint to UIButton's subview, 'UILabel' of a certain dimension.

Upvotes: 1

Views: 199

Answers (2)

Frederick C. Lee
Frederick C. Lee

Reputation: 9513

Based on the feedback... I got the correct solution:

myLabel1.setTranslatesAutoresizingMaskIntoConstraints(false)

Upvotes: 1

Earl Grey
Earl Grey

Reputation: 7466

Try adding

label.translatesAutoresizingMaskIntoConstraints = NO

to the top of your code

Upvotes: 1

Related Questions