三 2. 自动布局之Autoresizing、Autolayout(一)
4. Autoresizing简介
-
在Autolayout之前,有Autoresizing可以作屏幕适配,但局限性较大,有些任务根本无法完成相比之下,Autolayout的功能比Autoresizing强大很多
-
xib使用Autoresizing
Autoresizing:外边的四个是相对于某一个方向的距离不变,中间两个是控件的高度和宽度相对于父控件缩放,
右边是效果图:
![]()
-
代码实现 Autoresizing 代码示例:
#import "ViewController.h" @interface ViewController () /** 蓝色 */ @property (nonatomic, strong) UIView *blueView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIView *blueView = [[UIView alloc] init]; blueView.backgroundColor = [UIColor blueColor]; blueView.frame = CGRectMake(0, 0, 250, 250); [self.view addSubview:blueView]; self.blueView = blueView; UIView *redView = [[UIView alloc] init]; redView.backgroundColor = [UIColor redColor]; redView.frame = CGRectMake(0, 150, 250, 100); redView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth; [blueView addSubview:redView]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGFloat w = 200 + arc4random_uniform(100); CGFloat h = 200 + arc4random_uniform(100); self.blueView.frame = CGRectMake(0, 0, w, h); } /** UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 << 0, 距离父控件左边的间距是伸缩的(不固定的) UIViewAutoresizingFlexibleRightMargin = 1 << 2, 距离父控件右边的间距是伸缩的(不固定的) UIViewAutoresizingFlexibleTopMargin = 1 << 3, 距离父控件顶部的间距是伸缩的(不固定的) UIViewAutoresizingFlexibleBottomMargin = 1 << 5, 距离父控件底部的间距是伸缩的(不固定的) 重点:上面的四个设置了相当于不打勾【Flexible:拉伸的意思】,下面的两个设置了相当于打钩 UIViewAutoresizingFlexibleWidth = 1 << 1, 宽度跟随父控件的宽度进行自动伸缩 UIViewAutoresizingFlexibleHeight = 1 << 4, 高度跟随父控件的高度进行自动伸缩 */ @end
屏幕适配预览功能:点击菜单栏--双环【可以显示两个编译区】 -- Preview 【如果没有,点击书形按钮选择Preview】,就可以查看预览效果了,还可以添加不同的机型,在预览功能中还可以点击成横屏。


浙公网安备 33010602011771号