UIView的autoresizingMask属性的使用

在iOS应用的开发过程中,经常会使用,setFrame的方式对UIView进行布局,

经常会使用计算的方式,如self.view.bounds.size.height - 20-44- Heignt等来计算Y的相对位置

我们知道上边的数字 20是status bar的高度,44是navigationBar的高度.

这样的写法没有什么错误,但是不利于代码的复用,比如一个ViewController在创建的时候,有可能有navigationController,也可能没有navigationController,在这种情况下,这个VIewController里边的子UIView的相对位置就可能出现偏差.

所以,本文主要介绍autoresizingMask属性,对UIVIew进行相对的布局。

假设如下的需求:

程序启动后,构建一个自定义的TabBar,始终显示在应用的底部,无论屏幕发生旋转,或者收到来电的情况下,都显示在应用的底部。(看起来,跟现在的很多微博客户端相似,它们多半都没有使用系统的tabbarcontroller方式,而是自己绘制的tabbar).

可以用如下的代码来实现

- (void)viewDidLoad  
{  
    [super viewDidLoad];  
    self.tabbar = [[[CustumTabBar alloc] init] autorelease];  
    [self.tabbar setFrame:CGRectMake(0, self.view.bounds.size.height -44, self.view.bounds.size.width, 44)];  
    self.tabbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth;  
    [self.tabbar setBackgroundColor:[UIColor blueColor]];  
    [self.view addSubview:self.tabbar];  
}  

 代码中,autoresizingMask设置为底部和宽度对齐,加上shouldAutorotateToInterfaceOrientation方法返回YES后,程序无论怎样转向,TabBar都会在应用的底部显示了。

同理,如果想让一个UIVIew始终都在屏幕中心,

可以设置它的Y为 ceilf((self.view.bounds.size.height - Height)/2),

 同时设置autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin 即可。

posted @ 2014-05-30 15:06  轩宇峰  阅读(385)  评论(0编辑  收藏  举报