Search code examples
swiftuiviewuibuttonconstraints

satisfying two auto layout constraints programmatically - Swift


I want to set a UIButton with autoLayout constraints:

Basically I want the height to be the multiplier of the container view height:

button.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.43).isActive = true

and if the height doesn't reach the constant of 44 I want to set it to 44, I added this:

button.heightAnchor(greaterThanOrEqualToConstant: 44).isActive = true

Obviously programmatically setting 2 constraints like this causes a conflict, is there a way for programmatically accomplishing these 2 prerequisites without causing a warning?


Solution

  • You will need to set lower priority for the "ratio" constraint

    let constraint = button.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.43)
    constraint.priority = .defaultHigh
    constraint.isActive = true
    

    if the engine still have troubles with figuring out the layout, you can try different priority value.

    UILayoutPriority documentation