The Cook
The Cook

Reputation: 1443

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

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?

Upvotes: 27

Views: 29292

Answers (7)

Cyril
Cyril

Reputation: 2818

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.

Upvotes: 1

Luke Van In
Luke Van In

Reputation: 5265

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

Upvotes: 78

Amit Jagesha シ
Amit Jagesha シ

Reputation: 1112

Try following code it may helps you

yourviewObject.frame=CGRectMake(yourviewObject.frame.origin.x,yourviewObject.frame.origin.y,self.view.frame.size.width,yourviewObject.frame.size.height)

Upvotes: -5

Rakesh Mandloi
Rakesh Mandloi

Reputation: 361

Simple you use only four constraints (i.e Top space,Bottom space,Leading space,Trailing space) for that container view.

Upvotes: 0

Santo
Santo

Reputation: 1651

If you want to give a View's frame to fix all devices then use this width and height

self.view.frame.size.width,self.view.frame.size.height

Or You can give auto layouts Top Bottom Trailing and Leading constraints by dragging the View to its edges.

Upvotes: 0

Ravi Vaishnav
Ravi Vaishnav

Reputation: 36

UIView *viw=[UIView alloc]init];
viw.frame=CGRectMake(x,y,CGFLOAT_MAX,h);

Upvotes: -3

H4Hugo
H4Hugo

Reputation: 2650

If you are using Interface Builder you could :

  • ctrl + clic your view and drag the blue arrow to the superview.

  • Hold shift and select "equal width" and "equal height"

  • Then go to the constraints of your view (little ruler icon) and set a multiplier like 0.5 to make your view width/height equal to half of its superview respective dimension.

Upvotes: -2

Related Questions