iOS: 在代码中使用Autolayout (1) - 按比例缩放和优先级

来源:互联网 发布:sql server导出数据库 编辑:程序博客网 时间:2024/05/23 01:57

首先说按比例缩放,这是在Interface Builder中无法设置的内容。而在代码中,使用NSLayoutConstraint类型的初始化函数中的multiplier参数就可以非常简单的设置按比例缩放。同时也可以设置不同NSLayoutAttribute参数来达到意想不到的效果,比如“A的Width等于B的Height的2倍”这样的效果。

OK,开始写代码,我们就拿一个简单的UIButton做示例,在ViewController中创建一个UIButton字段:

UIButton *btn;

命令这个Button水平居中,始终距离父View底部20单位的距离。然后高度是父View高度的三分之一。

最后使用KVO来监控Button的大小并实时输出到屏幕上。

代码:

- (void)viewDidLoad

{

    [super viewDidLoad];

   

    //创建UIButton,不需要设置frame

    btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [btn setTitle:@"mgen" forState:UIControlStateNormal];

    btn.backgroundColor = [UIColor greenColor];

    [self.view addSubview:btn];

    //禁止自动转换AutoresizingMask

    btn.translatesAutoresizingMaskIntoConstraints = NO;

   

    //居中

    [self.view addConstraint:[NSLayoutConstraint

                              constraintWithItem:btn

                              attribute:NSLayoutAttributeCenterX

                              relatedBy:NSLayoutRelationEqual

                              toItem:self.view

                              attribute:NSLayoutAttributeCenterX

                              multiplier:1

                              constant:0]];

   

    //距离底部20单位

    //注意NSLayoutConstraint创建的constant是加在toItem参数的,所以需要-20

    [self.view addConstraint:[NSLayoutConstraint

                              constraintWithItem:btn

                              attribute:NSLayoutAttributeBottom

                              relatedBy:NSLayoutRelationEqual

                              toItem:self.view

                              attribute:NSLayoutAttributeBottom

                              multiplier:1

                              constant:-20]];

   

    //定义高度是父View的三分之一

    [self.view addConstraint:[NSLayoutConstraint

                              constraintWithItem:btn

                              attribute:NSLayoutAttributeHeight

                              relatedBy:NSLayoutRelationEqual

                              toItem:self.view

                              attribute:NSLayoutAttributeHeight

                              multiplier:0.3

                              constant:0]];

   

    //注册KVO方法

    [btn addObserver:self forKeyPath:@"bounds" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionInitial context:nil];   

}

 

//KVO回调

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    if (object == btn && [keyPath isEqualToString:@"bounds"])

    {

        [btn setTitle:NSStringFromCGSize(btn.bounds.sizeforState:UIControlStateNormal];

    }

}


0 0
原创粉丝点击