iOS autoresizing布局

在对UIView以及其子类空间的布局方案有多种,今天温习了一下autoresizing布局

一、了解一下相关知识:

1、UIView其中一个属性为

  @property(nonatomic) UIViewAutoresizing autoresizingMask;    // simple resize. default is UIViewAutoresizingNone

  该布局方案主要是对该属性的设置

2、UIViewAutoresizing为可选类型( NS_OPTIONS、NS_ENUM略有不同)

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {

    UIViewAutoresizingNone                 = 0,   //不会随父视图的改变而改变

    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,   //自动调整view与父视图左边距,以保证右边距不变

    UIViewAutoresizingFlexibleWidth        = 1 << 1,   //自动调整view的宽度,保证左边距和右边距不变

    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,  //自动调整view与父视图右边距,以保证左边距不变

    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,  //自动调整view与父视图上边距,以保证下边距不变

    UIViewAutoresizingFlexibleHeight       = 1 << 4,  //自动调整view的高度,以保证上边距和下边距不变

    UIViewAutoresizingFlexibleBottomMargin = 1 << 5  //自动调整view与父视图的下边距,以保证上边距不变

};

二、想要在xib或者storyboard上使用此布局方案,要讲默认的布局方案(AutoLayout以及Size classes)关闭

在纯代码编程中使用此布局时需要注意:

  UIView的autoresizesSubviews属性为yes时(默认为yes),autoresizing才会生效。

 三、以xib为例

很久没有使用xib,刚使用过程中还出现一点以前遇到的问题:

loaded the "TestViewController" nib but the view outlet was not set.

解决方法:右击File's Owner ,在弹出列表中的view项右击连线到xib即可(即将此view设置为File's Owner的属性),如下图

休息片刻之后,继续回来:

下图中给橙色控件的autoresizingMask属性设置的值有四个UIViewAutoresizingFlexibleRightMargin、UIViewAutoresizingFlexibleWidth、UIViewAutoresizingFlexibleLeftMargin、UIViewAutoresizingFlexibleBottomMargin(顺序从左到右、从上到下),目的是让橙色button的左边距、右边距、上边距固定,宽度可变、高度不变,在任何尺寸的屏幕下都是如此!

 此效果用代码显示的话为

 self.view.autoresizesSubviews = YES;

    CGFloat margin = 8;

    CGFloat buttonY = 65;

    CGFloat height = 143;

    CGFloat width = [UIScreen mainScreen].bounds.size.width - margin * 2;

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(margin, buttonY, width, height)];

    [btn setTitle:@"Autoresizing" forState:UIControlStateNormal];

    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [btn setBackgroundColor:[UIColor orangeColor]];

    [self.view addSubview:btn];

     // autoresizing布局

    btn.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;

即可展示和xib一样的效果

在此过程中,出现个小小的问题,就是横屏、竖屏切换过程中,导航栏高度变化,会导致上边距有变化(效果上看来是上边距变化),

想了一下解决办法,代码如下

self.edgesForExtendedLayout = UIRectEdgeNone; // 布局时忽略导航栏高度(iOS7之后的属性)

这样就可以避免导航栏高度随横竖屏切换变化对布局产生的影响! 

   

原文地址:https://www.cnblogs.com/Ice-snowPride/p/5788526.html