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
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];
}
You can specify more than one lineBreakMode on a label by using the bitwise OR operator.
For example, the following code would wrap the text of the label, and would add the ellipsis on the tail end of the text when it expanded beyond the size of the label's frame height.
lblTemp.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
lblTemp.numberOfLines = 0;
UPDATE: this is not correct. It appears to work because UILineBreakModeWordWrap
is 0 in the enum. See comments below.