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

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

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

UIViewAutoresizing 的属性定义如下:

enum {

    UIViewAutoresizingNone                 = 0,

    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,

    UIViewAutoresizingFlexibleWidth        = 1 << 1,

    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,

    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,

    UIViewAutoresizingFlexibleHeight       = 1 << 4,

    UIViewAutoresizingFlexibleBottomMargin = 1 << 5

};

typedef NSUInteger UIViewAutoresizing;


UIViewAutoresizingNone 默认是None,也就是当父视图的大小变动时,设置的子view不做任何适应操作

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-3000300300);

    right.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    [right setTitle:@"456" forState:UIControlStateNormal];

    [self.view addSubview:right];

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值