UILabel實現文本自適應方法(ios7)
- (void)initUserInterface
{
UILabel *label = [[UILabel alloc]init];
label.numberOfLines = 0; // 需要把顯示行數設置成無限制
label.font = [UIFont systemFontOfSize:15];
label.textAlignment = NSTextAlignmentCenter;
label.text = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
CGSize size = [self sizeWithString:label.text font:label.font];
label.bounds = CGRectMake(0, 0, size.width, size.height);
label.center = self.view.center;
[self.view addSubview:label];
}
// 定義成方法方便多個label調用 增加代碼的復用性
- (CGSize)sizeWithString:(NSString *)string font:(UIFont *)font
{
CGRect rect = [string boundingRectWithSize:CGSizeMake(320, 8000)//限制最大的寬度和高度
options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin//采用換行模式
attributes:@{NSFontAttributeName: font}//傳人的字體字典
context:nil];
return rect.size;
}