UILabel是这样创建的:
label = [[UILabel alloc] initWithFrame:CGRectMake(32, 10, 268, 44)];
label.textAlignment = NSTextAlignmentLeft;
label.backgroundColor = [UIColor yellowColor];
label.numberOfLines = 2;
label.lineBreakMode = NSLineBreakByTruncatingTail;
然后更新标签我这样做:
label.text = someText;
CGRect frame = label.frame;
NSDictionary *attributes = @{NSFontAttributeName: label.font};
CGRect rect = [someText boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
frame.size.height = rect.size.height;
label.frame = frame;
这很好用,标签只有一行文字,但我最多有两行。当第二行被截断时,额外的底部填充会被添加到标签中,这使得无法在其下方放置标签(图像中的红色标签):
为什么会这样?如果它是一个错误,是否有解决方法?
答案 0 :(得分:0)
尝试这样的事情:
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:text attributes:attributes];
UILabel *anotherLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, myLabel.frame.size.width, MAXFLOAT)];
[anotherLabel setAttributedText:attrString];
[anotherLabel setNumberOfLines:2];
[anotherLabel setText:NSTextAlignmentLeft];
[anotherLabel setLineBreakMode:NSLineBreakByTruncatingTail];
[anotherLabel sizeToFit];
[myLabel setAttributedText:attrString];
[myLabel setFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, [anotherLabel frame].size.height)];