How can I set maximum width of a view in iOS?

You can do this programmatically

some_view.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, multiplier: 0.45)        
some_view.heightAnchor.constraint(lessThanOrEqualTo: view.widthAnchor multiplier: 0.45)

0.45 is basically saying the width and height of some_view will be at maximum 45% of the width of the super view.


You can use auto-layout constraints so that the box adapts to the screen size, but does not exceed a given width and height. To do this, set a "less than or equal to" constraint on the width and height.

  1. Add top, bottom, leading, trailing, width and height constraints to the box.
  2. Set the priority of the top, bottom, leading and trailing constraints to High (750).
  3. Set the relation for the width and height constraints to Less Than or Equal (≤). The default value is Equal.
  4. Set the priority of the width and height constraints to Required (1000).
  5. Set the constant of the width and height constraints to the maximum size you want the box to be.

Set width constraint relation to Less Than or Equal

Set width constraint constant to 1000

Set leading and trailing constraint priority to 750

Tags:

Ios

Autolayout