我已经在我的 iOS 5/6 应用程序中使用这段代码很长时间了。它位于 viewWillAppear:
下并操纵 UILabel
高度,以便它可以根据需要容纳更多文本(并将其下方的其他标签向下推)。问题是,对于 iOS 7,它似乎不再工作了。文本根本不会换行到第二行。这是代码:
self.titleLabel.text = titleString;
self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.titleLabel.numberOfLines = 0;
// Determine what the size of the title label should be
CGSize maximumLabelSize = CGSizeMake(163,66);
CGSize expectedLabelSize = [titleString sizeWithFont:self.titleLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:self.titleLabel.lineBreakMode];
// Adjust the the new height of the title label.
CGRect newFrame = self.titleLabel.frame;
newFrame.size.height = expectedLabelSize.height;
self.titleLabel.frame = newFrame;
NSLog(@"Title Height: %f", self.titleLabel.frame.size.height);
这里有更多信息。此 UILabel
位于 UITableView
的标题 View 中。它是使用 Interface Builder 和标签的 IBOutlet
设计的。 UILabel
的属性在 iOS 6 和 iOS 7 项目中是相同的。
这是针对 iOS 6 运行 Xcode 4 时的样子:
这是带有 iOS 7 的 Xcode 5(如您所见,文本没有结束):
有人有什么想法吗?
最佳答案
就像@Jack Wu 说的,试着给标签增加几个像素。同样是 iOS 7 sizeWithFont
被替换为 boundingRectWithSize
:
GSize maximumLabelSize = CGSizeMake(163,66);
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:titleString attributes:@{NSFontAttributeName: self.titleLabel.font}];
CGRect rect = [attributedText boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize expectedLabelSize = rect.size;
关于ios - 为什么我的 UILabel 框架代码在 iOS 6 中有效,但在 iOS 7 中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708864/