Masonry布局控件,自动换行

1,823 阅读1分钟

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