How To Fix Swift Error LayoutConstraints Unable To Simultaneously Satisfy Constraints

When i add swift constraints to button programmatically in source code, i meet an error message like this. [LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don’t want.  

This error message confuse me a lot of time, but after investigate through google, i finally find the solution to fix this error. This is because swift do not allow change UI component constraints programmatically in source code by default.

If you want to apply constraints to UI component in swift source code programmatically,  you must first set the UI component’s property translatesAutoresizingMaskIntoConstraints‘s value to false like below, then the error will disappear when you add constraints to the button.

var button = UIButton(type: UIButton.ButtonType.system)

// Set button property to change it's title, color, background etc.

// Below code will allow you to add custom constraints to this button programmatically. 
button.translatesAutoresizingMaskIntoConstraints = false

// Create constraints object, below constraints set above button's top edge 100 point away from screen safe area top. 
let topConstraint = NSLayoutConstraint.init(item: button, attribute:, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute:, multiplier: 1.0, constant: 100)

// Active above constraint variable by set it's isActive property to true, otherwise this constraint will not take effect.
topConstraint.isActive = true

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.