How to set dynamic width & height of a view in autolayout in iOS?

雨燕双飞 提交于 2019-12-18 19:15:07

问题


I have a UIView in my super view.I have set it some constraints.Now I want the size of view should be different on different devices.If I set the fix width & height then I get the wrong result.I have tried to user aspect ratio but that make a view too big or too small on multiple devices.

I want the height & width should increase in equal proportion that it must look same all devices.I want to have flexible height and width of the view.Please tell how to do this?

Here is the image

Thanks in Advance


回答1:


Use Size Classes. It helps to have different settings for different devices. http://www.raywenderlich.com/83276/beginning-adaptive-layout-tutorial https://youtu.be/IwSTXY0awng?t=2m12s




回答2:


The most simple way is create a Outlet of your width and height constraint.

Then dynamically change it in viewDidLoad according to phone.

To check which phone it is u can check the device height like 480 for iPhone 4S ,568for iPhone 5,5S and etc

@interface ScoreListViewController (){
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *widthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;

@end



- (void)viewDidLoad {
[super viewDidLoad];
// Set the value according to your requirement
if(4S){
self.heightConstraint.constant=100;
}

 }



回答3:


Try to follow the screen shots as below:

You will get the result as below




回答4:


I have written a blog article about autolayouting for dynamically changing layouts.
For each screen size you can programmatically add the constraints.
Algorithm

  1. Get the current device size
  2. Get the required constraints according to the device size
  3. Then programmatically add the constraints


Changing according to orientation

  • Listen to the UIDeviceOrientationDidChangeNotification notifiation
  • Add new constraints according to the notification
  • Then call setNeedsUpdateConstraints
    For more info and a example code, look at the blog article and this github repo


来源:https://stackoverflow.com/questions/30777528/how-to-set-dynamic-width-height-of-a-view-in-autolayout-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!