码迷,mamicode.com
首页 > 其他好文 > 详细

开发细节(二)

时间:2015-02-06 13:00:51      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:

1. 利用Auto Layout整体排列控件

下面的代码演示了一个控件如何在其父容器中垂直水平居中:

UIView *box = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 150)];
box.backgroundColor = [UIColor grayColor];
[self.view addSubview:box];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"a button" forState:UIControlStateNormal];
[button sizeToFit];
button.translatesAutoresizingMaskIntoConstraints = NO;
[box addSubview:button];

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObjectsFromArray:[NSLayoutConstraint
                            constraintsWithVisualFormat:@"V:[box]-(<=1)-[button]"
                            options:NSLayoutFormatAlignAllCenterX
                            metrics:nil
                            views:NSDictionaryOfVariableBindings(box,button)]];

[array addObjectsFromArray:[NSLayoutConstraint
                            constraintsWithVisualFormat:@"H:[box]-(<=1)-[button]"
                            options:NSLayoutFormatAlignAllCenterY
                            metrics:nil
                            views:NSDictionaryOfVariableBindings(box,button)]];

[box addConstraints:array];

下面的代码演示了多个控件其父容器中水平左对齐,垂直居中:

UIView *box = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 150)];
box.backgroundColor = [UIColor grayColor];
[self.view addSubview:box];
    
UILabel *label = [[UILabel alloc] init];
label.text = @"a label";
[label sizeToFit];
label.backgroundColor = [UIColor redColor];
label.translatesAutoresizingMaskIntoConstraints = NO;
[box addSubview:label];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"a button" forState:UIControlStateNormal];
[button sizeToFit];
button.translatesAutoresizingMaskIntoConstraints = NO;
[box addSubview:button];

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObjectsFromArray:[NSLayoutConstraint
                            constraintsWithVisualFormat:@"V:|-[button]-|"
                            options:NSLayoutFormatAlignAllLeft
                            metrics:nil
                            views:NSDictionaryOfVariableBindings(button)]];

[array addObjectsFromArray:[NSLayoutConstraint
                            constraintsWithVisualFormat:@"|-15-[myLabel]-5-[myButton]"
                            options:NSLayoutFormatAlignAllCenterY
                            metrics:nil
                            views:@{@"myLabel":label, @"myButton":button}]];

[box addConstraints:array];

 

开发细节(二)

标签:

原文地址:http://www.cnblogs.com/wayne23/p/4276705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!