让系统自动控制控件在控制器视图的位置

IPhone、IPad经常会遇到横竖屏切换,或者需要自动调整大小。如果你的界面不能用storyboard和xib来生成界面的话,先把控制器视图的frame属性值固定下来,然后添加subview(子视图)的时候,就可以使用视图继承类(UIView) 自带的 autoresizingMask 属性,之后如果横竖屏切换,或者是使用UIPopoverController之类的方法,就可以只设置一次frame属性,以后的frame属性都是自适应的(frame缩小太多的话效果不好,根据情况而定)。

 
原理:设置autoresizingMask后,当页面的大小发生改变,那么系统会给已经显示的所有有关的子视图进行自动调整。属性中的所有控件根据 autoresizingMask 来自动设置属性 frame,你能在对应的 -(void)setFrame:(CGRect)rect{} 实现系统的回调,在调用 setFrame 方法的过程中,系统会自动加载默认的动画方法。

UIViewAutoresizing 的属性定义如下:

 {

    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];

}
原文地址:https://www.cnblogs.com/limicheng/p/3841120.html