【发布时间】:2014-11-17 12:58:36
【问题描述】:
我有一个可以接受可变长度字符串的 UILabel。标签应该扩展以接受它给出的任何长度的字符串。我在 iOS7 中有这个工作,但在 iOS8 中,标签是单行的,当文本太长时,文本会被截断。行数设置为 0。这是我在 iOS7 中工作的代码:
- (IBAction)btnClicked:(id)sender {
[_theLabel setText:[_txtLabel text]];
CGSize constrainedSize = CGSizeMake(_theLabel.frame.size.width, 9999);
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17.0], NSFontAttributeName, nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[_txtLabel text] attributes:attributesDict];
CGRect requireHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if(requireHeight.size.width > _theLabel.frame.size.width){
requireHeight = CGRectMake(0, 0, _theLabel.frame.size.width, requireHeight.size.height);
}
CGRect newFrame = _theLabel.frame;
newFrame.size.height = requireHeight.size.height;
[self.theLabel setFrame:newFrame];
}
对于 iOS8 的变化有什么建议吗?谢谢!
【问题讨论】:
-
使用自动布局,无需任何代码即可实现。设置框架后你有没有尝试调用
[label setNeedsLayout]?
标签: ios objective-c uilabel