IPhone、IPad经常会遇到横竖屏切换,或者需要自动调整大小。如果你的界面不能用storyboard和xib来生成界面的话,先把控制器视图的frame属性值固定下来,然后添加subview(子视图)的时候,就可以使用视图继承类(UIView) 自带的 autoresizingMask 属性,之后如果横竖屏切换,或者是使用UIPopoverController之类的方法,就可以只设置一次frame属性,以后的frame属性都是自适应的(frame缩小太多的话效果不好,根据情况而定)。
{
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;
UIViewAutoresizingFlexibleLeftMargin 视图靠右对齐
UIViewAutoresizingFlexibleWidth 视图自适应宽度
UIViewAutoresizingFlexibleRightMargin 视图靠左对齐
UIViewAutoresizingFlexibleTopMargin 视图靠下对齐
UIViewAutoresizingFlexibleHeight 视图自适应高度
UIViewAutoresizingFlexibleBottomMargin 视图靠上对齐
注意:LeftMargin、RightMargin、TopMargin、BottomMargin的实际对齐方向是相反的
示例:让按钮始终在 ViewController 的右上角显示:
- ( void )viewDidLoad { [super viewDidLoad]; UIButton *right = [UIButton buttonWithType:UIButtonTypeRoundedRect]; right.frame = CGRectMake(self.view.frame.size.width- 300 , 0 , 300 , 300 ); right.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [right setTitle: @" 456 " forState:UIControlStateNormal]; [self.view addSubview:right]; }