iOS 多个不同宽度button布局自动换行

mark下需要循环布局不同宽度button的情况,根据button宽度自动换行。

#pragma mark - 多个不同宽度button自动换行
-(void)createViewWithTitleArr
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 250, WID, 45)];
    bgView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:bgView];
    
    NSArray *titleAry = @[@"安徽发克鲁斯",
                          @"啥就开始打开",
                          @"等哈说楼房吉安老师发货啦",
                          @"盛开的花",
                          @"就发生;楼房吉安;十分骄傲;十分骄傲;是否"];
    CGFloat pointX = 10.0; //button X坐标
    CGFloat pointY = 10.0; //button Y坐标
    CGFloat padding = 5.0; //button 间距
    CGFloat btnHeight = 30; //button高度
    CGFloat allWidth = WID - 10;
    UIFont *titleFont = [UIFont systemFontOfSize:15];
    for (int i = 0; i < titleAry.count; i++) {
        CGRect rect = [titleAry[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, 30) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : titleFont} context:nil];
        CGFloat btnWidth = rect.size.width + 20;
        
        if (pointX + btnWidth > allWidth) {//换行
            pointX = 10;//X从新开始
            pointY += (btnHeight + padding);//换行后Y+
        }
        UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
        but.frame = CGRectMake(pointX, pointY, btnWidth, btnHeight);
        but.tag = i + 1000;
        [but addTarget:self action:@selector(clickButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        but.layer.masksToBounds = YES;
        but.layer.cornerRadius = btnHeight/2;
        but.layer.borderWidth = 1;
        but.layer.borderColor = [UIColor magentaColor].CGColor;
        [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [but setTitle:titleAry[i] forState:UIControlStateNormal];
        but.titleLabel.font = titleFont;//一定要一样
        pointX += (btnWidth + padding);//每次X都加上button宽和间距5
        
        [bgView addSubview:but];
    }
    CGRect rect2 = bgView.frame;
    rect2.size.height = pointY + btnHeight + 10;
    bgView.frame = rect2;
}

-(void)clickButtonAction:(UIButton *)sender
{
    if (sender.selected) {
        return;
    }
    _tempButton.selected = NO;
    _tempButton.backgroundColor = [UIColor clearColor];

    sender.selected = YES;
    sender.backgroundColor = [UIColor magentaColor];
    _tempButton = sender;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值