How to set up an auto layout constraint to be a % value

I'm setting up auto layout constraints and I want the leading constraint of one of the controls on the view to be a fixed value on iPhone (CR) and equal to a % of the screen width for iPad. Can this be done in IB using the size inspector or does it need to be done programmatically? I've searched for documentation and looked at lots of videos but I was unable locate the information. If someone could provide a link to the documentation or share some sample code, I would be very grateful.

Replies

It is possible in IB. May be with some limits.

  • you have to define constraints, for different variations
  • Define the first constraint (will be for iPhone)
  • define a variation hC (compact height) and Width Any and a variation for wC (compact width) and height any
  • create another constraint that will be used for iPad
  • define a variation hR (regular height) and Width Any and a variation for wR (regular width) and height any.
  • set the multiplier value to what you need (between 0 and 1, not in percent).

However, that may cause problem with large iPhones. If so, you will have to

  • create a unique constraint
  • set its value (constraint.constant) programmatically depending on device type
  • That is often the simplest.
  • Thank you, Claude. Your first method doesn't make the constraint value a % of the screen width, or does it? I've been using the second method already. I was thinking autolayout word be a better way to go. Most of my UI is set up to make the constraint values a % of the screen height/width. I've been setting the control to centered and adjusting the leading constraint using the screen width/height. Makes for cleaner layout. I guess I'll have to rethink the way I was planning to use autolayout.

Add a Comment