個人感覺,現階段IOS開發必備技能—–AutoLayout。蘋果公司也一直在推薦這個佈局方法。現在我們來簡單瞭解一下。直接上代碼:
UIView *backgroundView = [[UIView alloc] init];
[backgroundView setTranslatesAutoresizingMaskIntoConstraints:NO];
backgroundView.backgroundColor = [UIColor blueColor];
[self.view addSubview:backgroundView];
//UILabel
UILabel *textInfoLabel = [[UILabel alloc] init];
[textInfoLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
textInfoLabel.backgroundColor = [UIColor redColor];
textInfoLabel.numberOfLines = 0;
textInfoLabel.font = [UIFont systemFontOfSize:15];
textInfoLabel.text = @"測試";
[self.view addSubview:textInfoLabel];
NSDictionary *views = @{@"backgroundView":backgroundView, @"textInfoLabel":textInfoLabel};
NSDictionary *metrics = @{@"LeftStep":@20, @"TopStep":@30, @"Width":@200, @"Height":@"100", @"VStep":@20, @"HStep":@20};
//垂直方向 @“垂直方向:|-距離頂部-[backgroundView(==Width)]-兩個view之間的垂直距離-[textInfoLabel(>=一行字的高度)]”
NSString *vLayoutString = @"V:|-TopStep-[backgroundView(==Width)]-VStep-[textInfoLabel(>=20)]";
NSArray *vLayoutArray = [NSLayoutConstraint constraintsWithVisualFormat:vLayoutString options:0 metrics:metrics views:views];
//水平方向 @"水平方向:|-距離左邊-[backgroundView(==水平高度(寬度))-兩個view之間的水平距離-[]]
NSString *hLayoutstring = @"H:|-LeftStep-[backgroundView(==Height)]-HStep-[textInfoLabel(==120)]";
NSArray *hLayoutArray = [NSLayoutConstraint constraintsWithVisualFormat:hLayoutstring options:0 metrics:metrics views:views];
[self.view addConstraints:vLayoutArray];
[self.view addConstraints:hLayoutArray];