masonry
偏移量offset
答疑:
假設子控制元件在父控制元件的內部,設定距離父控制元件的上左下右都為10,那麼相關程式碼為:
make.top.equalTo(self.view).offset(10);
make.left.equalTo(self.view).offset(10);
make.bottom.equalTo(self.view).offset(-10);
make.right.equalTo(self.view).offset(-10);
複製程式碼
上左為正,下右為負,這一切的一切都是因為在iOS系統中座標系的遠點是左上角,圖裡解釋的很清楚了。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//依次建立button 距離左右均為15
NSArray *array = @[@"劉德華", @"劉德華,劉德華",@"劉德華華",
@"劉",@"劉德德華",@"劉德華,劉德華",
@"劉德華,劉德華", @"劉德華,劉德華", @"劉德華,劉德華",
@"劉德華,", @"劉德華,劉德華", @"劉德",
@"劉德華,劉德華", @"劉德華,", @"劉德華,劉德華",
@"劉德華,劉德華", @"劉德華,劉德華", @"劉德華,",
@"劉德華,劉德"];
//存放上一個button
UIButton *buttonBefore;
//存放button距離左側的寬度,來確定是否需要換行
__block CGFloat right = 0.0;
//間距
CGFloat margin = 15.f;
for(int i=0; i<array.count; i++){
NSString *str = [array objectAtIndex:i];
CGFloat fitWidth = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}].width + 30;
UIButton *button = [[UIButton alloc] init];
[button setTitle:str forState:UIControlStateNormal];
button.backgroundColor = [UIColor lightGrayColor];
[button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[self.view addSubview:button];
[button mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(fitWidth);
make.height.mas_equalTo(20);
if(i==0){
make.left.equalTo(self.view).offset(margin);
make.top.equalTo(self.view).offset(80);
right = margin + fitWidth + margin;
}else{
if(right+fitWidth > [UIScreen mainScreen].bounds.size.width){
make.top.mas_equalTo(buttonBefore.mas_bottom).offset(margin);
make.left.equalTo(self.view).offset(margin);
right = margin+fitWidth+margin;
}else{
make.left.mas_equalTo(buttonBefore.mas_right).offset(margin);
make.top.equalTo(buttonBefore);
right += fitWidth+margin;
}
}
}];
buttonBefore = button;
}
}
複製程式碼