我需要将多行属性文本适配到UILabel的框架中。
阅读这个主题如何调整标签字体大小以适应矩形?我从Niels的解决方案开始,以便处理带属性的文本。
以下是代码:'prospect'的't'被放在新行中,但我需要单词不被截断;在这个例子中,我期望字体大小进一步减小,以适应'prospect'在一行中。
以下是代码:'prospect'的't'被放在新行中,但我需要单词不被截断;在这个例子中,我期望字体大小进一步减小,以适应'prospect'在一行中。
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 180, 180)];
myLabel.font = [UIFont fontWithName:@"Arial" size:5];
myLabel.adjustsFontSizeToFitWidth = YES;
myLabel.backgroundColor = [UIColor orangeColor];
myLabel.numberOfLines = -1;
myLabel.lineBreakMode = NSLineBreakByWordWrapping;
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing:8];
[paragraphStyle setAlignment:NSTextAlignmentLeft];
NSDictionary *attributes = @{ NSFontAttributeName:myLabel.font, NSParagraphStyleAttributeName: paragraphStyle };
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"New Prospect" attributes:attributes];
myLabel.attributedText = attributedString;
myLabel.font = [UIFont fontWithName:@"Arial" size:160];
[self sizeLabel:myLabel toRect:myLabel.frame];
[self.view addSubview:myLabel];
sizeLabel方法的实现如下:
- (void) sizeLabel {
int fontSize = self.font.pointSize;
int minFontSize = 5;
// Fit label width wize
CGSize constraintSize = CGSizeMake(self.frame.size.width, MAXFLOAT);
do {
// Set current font size
self.font = [UIFont fontWithName:self.font.fontName size:fontSize];
// Find label size for current font size
CGRect textRect = [[self attributedText] boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize labelSize = textRect.size;
// Done, if created label is within target size
if( labelSize.height <= self.frame.size.height )
break;
// Decrease the font size and try again
fontSize -= 2;
} while (fontSize > minFontSize);
}
有什么想法吗? 谢谢, DAN