Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

autolayout

My app have a basic login screen, an outer box and in it, some text fields and buttons. I set the box to fill the screen. However, on some devices this box will be too big. How do I set maximum width and height to a view?

like image 823
The Cook Avatar asked Jul 11 '16 13:07

The Cook


2 Answers

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

like image 182
Luke Van In Avatar answered Oct 14 '22 07:10

Luke Van In


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.

like image 35
Cyril Avatar answered Oct 14 '22 06:10

Cyril