美文网首页
UIButton长度自适应文字长度

UIButton长度自适应文字长度

作者: MoneyLee | 来源:发表于2016-12-25 23:32 被阅读437次

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

相关文章

网友评论

      本文标题:UIButton长度自适应文字长度

      本文链接:https://www.haomeiwen.com/subject/qpidvttx.html