UIButton长度自适应文字长度

- (void)createUI{ CGFloat w = 0; CGFloat h = 10; for (int i = 0; i< self.nameArray.count; i++) {

    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    //获取文字的长度
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
    CGFloat length = [self.nameArray[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
//    btn.frame = CGRectMake(15+(i%3)*120, 80+(i/3)*40, length + 15, 30);
    btn.frame = CGRectMake(10 + w, h, length + 15 , 30);
    
    //当大于屏幕的宽度自动换
    if (10 + w + length + 15 > SCREEN_WIDTH)
    {
        w = 0;
        h = h + btn.frame.size.height + 10;
        btn.frame = CGRectMake(10 + w, h, length + 15 , 30);
    }
    w = btn.frame.size.width + btn.frame.origin.x;

    [btn setTitle:self.nameArray[i] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(smallBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = i+10;
    btn.layer.cornerRadius = 5;
    btn.layer.borderWidth = 2;
    btn.layer.borderColor = [UIColor yellowColor].CGColor;
    btn.clipsToBounds = YES;

    [self.view addSubview:btn];
}
复制代码

转载于:https://juejin.im/post/5a320715f265da4309452cc1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值