UIButton's Title Label Word Wrap with Tail Truncation

前端 未结 8 1326
暖寄归人
暖寄归人 2020-12-24 03:11

I need to enable word wrapping and tail truncation, at the same time, on a UIButton\'s titleLabel. Setting numberOfLines to something more than 0 d

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 03:39

    button.titleLabel.numberOfLines = 2;
    button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    UIFont * theFont = [UIFont systemFontOfSize: 14]; // you set
    CGSize textSize = [titleStr sizeWithAttributes:@{NSFontAttributeName: theFont}];
    CGFloat theWidth = kScreenWidth-otherWidthYouSet;// I thought the button's frame is content driving ,and is limited 
    CGFloat ratio = theWidth*heightYouSet/((textSize.width+4)*(textSize.height+6));// 4 , 6 , is made by experience . I think the textSize is taken one line text default by the system 
    NSUInteger validNum = ratio * titleStr.length;
    
    if(ratio<1){
        [button setTitle: [[titleStr substringToIndex: validNum] stringByAppendingString: @"..."] state: yourState];
    
    }
    else{
        [button setTitle: titleStr state: yourState];
    }
    

提交回复
热议问题