2013-11-29 52 views
0

所以,我想讓一些文字適合 我已經使用Resizing UILabel to fit with Word Wrap的答案來使文字合適。這似乎工作,除了文本嚴重縮小,只佔約50%的屏幕寬度。UILabel多行文字縮放字體要符合 n

這是一個運行在視圖控制器提供的代碼:

self.user.title = @"Jeffrey C. Louie\n2326 Rockford Road\nCharlestown, MA 02129"; 
[self.titleLabel setText:self.user.title]; 

NSInteger fsize = 200; 
[self.titleLabel setFont:[UIFont fontWithName:self.titleLabel.font.fontName size:fsize]]; 

float height = [self.user.title sizeWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(self.titleLabel.bounds.size.width, 99999) lineBreakMode:NSLineBreakByWordWrapping].height; 

while (height > self.titleLabel.bounds.size.height && height != 0) { 
    fsize -=1; 
    [self.titleLabel setFont:[UIFont fontWithName:self.titleLabel.font.fontName size:fsize]]; 
    height = [self.user.title sizeWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(self.titleLabel.bounds.size.width, 99999) lineBreakMode:NSLineBreakByWordWrapping].height; 
} 

for (NSString *word in [self.user.title componentsSeparatedByString:@" "]) { 
    float width = [word sizeWithFont:self.titleLabel.font].width; 
    while (width > self.titleLabel.bounds.size.width && width != 0) { 
     fsize -= 3; 
     [self.titleLabel setFont:[UIFont fontWithName:self.titleLabel.font.fontName size:fsize]]; 
     width = [word sizeWithFont:self.titleLabel.font].width; 
    } 
} 

example of text not fitting the view correctly

在我看來,該文已經被調整以適合1行,如果所有文字強硬的換行符不存在。有沒有辦法讓UILabel知道是否存在換行並相應地縮放行文本?

感謝

回答

0

可以使用RTLabel相反的UILabel, 並更換新行字符的html<br>標籤。 Like:

RTLabel *label = [[RTLabel alloc] initWithFrame:/*your frame*/]; 
NSString htmlText = [yourText stringByReplacingOccurrencesOfString:@"\\n" withString:@"<br>"]; 
[label setText:htmlText]; 
[yourView addSubView:label];