3

I'm working on an iPhone app in Xcode 6 and I have set the constraints for my view. I want to ensure that a UIButton doesn't go off the page or lose its aspect ratio on extreme sized devices.

UIButton is center on the view using constraints UIButton is limited on the horizontal edges to the margins

The issue is that on a iPhone 6 plus the button is HUGE. How do I set the max size for my UIButton? I want it to scale, but once it reaches 150x150 I want it to no longer grow.

Thanks

Marcus
  • 9,032
  • 11
  • 45
  • 84

1 Answers1

12

You create a Width less Than or Equal 150 constraint. That works because the button has a intrinsic width, so the constraint limits it to a max width of 150 pt.
But this would conflict with your edge constraints because they want to make the button wider than 150 points. If you lower the priority of the edge constraints the width constraint gets precedence. The edge constraints will be only fulfilled if they don't break the width constraint. The edge constraints don't disappear, they still assert some "pull" on the button, but they can't assert their full "force". So they just pull it to the max width of 150 points.

This is how you do it:

Create a "regular" width constraint, then edit that constraint in the side bar so it becomes a "Less Than or Equal" constraint.

enter image description here

Next you select the edge constraints and lower their priority to something less than 1000.

enter image description here

And you got a button that grows until it's 150 points wide.

enter image description here

in code:

let button = UIButton()
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.backgroundColor = UIColor.redColor()
button.setTitle("Button", forState: .Normal)
view.addSubview(button)

let centerXConstraint = NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0)
view.addConstraint(centerXConstraint)
let centerYConstraint = NSLayoutConstraint(item: button, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
view.addConstraint(centerYConstraint)

let views = ["button" : button]

let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|-(100@999)-[button(<=150)]-(100@999)-|", options: nil, metrics: nil, views: views)
view.addConstraints(horizontalConstraints)

last two lines contain the important constraints.

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247