Ad

NSLayoutConstraint Not Working On Uibutton And Uilabel

- 1 answer

I create one uilable and uibutton

@IBOutlet weak var label_one: UILabel!
@IBOutlet weak var btn_one: UIButton!

and set following trailing and leading constraints

        self.btn_one.translatesAutoresizingMaskIntoConstraints=false
    let contariants=NSLayoutConstraint(item:self.view,attribute:NSLayoutAttribute.LeadingMargin , relatedBy: NSLayoutRelation.Equal, toItem: btn_one, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1.0, constant: 20)
    let trailingConstraints=NSLayoutConstraint(item: self.view, attribute:NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: btn_one, attribute:NSLayoutAttribute.Trailing , multiplier: 1.0, constant:20 )

    self.view.addConstraint(contariants)
    self.view.addConstraint(trailingConstraints)

// but it not working at all and giving following warnings 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. ( "", "UIButton:0x7ff8c84b0b60'Button' (Names: '|':UIView:0x7ff8c85226d0 )>" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful. 2015-12-16 10:39:01.918 ConstraintsExample[2635:38168] 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. ( "", "UIButton:0x7ff8c84b0b60'Button' (Names: '|':UIView:0x7ff8c85226d0 )>", "", "" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful.

Ad

Answer

This error is cause you are trying to make the view do multiple constraints at the same time. The instant you drag n drop an element on the view from IB, it makes a basic constraint of the given location. When you attempt the following "addConstraint" method the compilier is unable to understand which constraint to follow.

The above will work if u programmatically make a button and label. PFB a post that talk about this:

Programmatically Add CenterX/CenterY Constraints

In case you want to modify your existing constraints on the storyboard: Add a constraint on the element: adding an element contraint

No use that contraint as a connection to your code: make the constraint part of the code

Ad
source: stackoverflow.com
Ad