iOS autoresizing布局

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

 

1、了解一下相关知识:布局

一、UIView其中一个属性为atom

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

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

二、UIViewAutoresizing为可选类型( NS_OPTIONS、NS_ENUM略有不一样)blog

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {it

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

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

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

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

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

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

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

};

 

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

 

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

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

 

 3、以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以后的属性)

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

相关文章
相关标签/搜索