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

2. ScrollView利用Auto Layout管理控件

开发细节(二)

3. IB_DESIGNABLE,IBInspectable配合XIB实现自定义控件

#import <UIKit/UIKit.h>

@interface MyTempView : UIView

@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UILabel *myLabel;

@end
MyTempView.h

相关文章: