你可以得到的UILabel的確切高度恰好與路過相同的字體大小和類型,並做一些計算。
在這裏,我使用Helvetica字體一個UILabel與字體大小16.
目標C
- (CGFloat)requiredHeight:(NSString*)labelText{
UIFont *font = [UIFont fontWithName:@"Helvetica" size:16.0];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, CGFLOAT_MAX)];
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.font = font;
label.text = labelText;
[label sizeToFit];
return label.frame.size.height;
}
輸出
CGFloat size = [self requiredHeight:@"iOS Rocks"];
NSLog(@"%f",size);
size = [self requiredHeight:@"iOS Rocks\n"];
NSLog(@"%f",size);
控制檯輸出
2016-04-10 01:37:46.812 testPro[6093:327503] 18.500000
2016-04-10 01:37:46.814 testPro[6093:327503] 37.000000
雨燕2.2
func requiredHeight(labelText:String) -> CGFloat {
let font = UIFont(name: "Helvetica", size: 16.0)
let label:UILabel = UILabel(frame: CGRectMake(0, 0, 200, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = labelText
label.sizeToFit()
return label.frame.height
}
編輯
雨燕3.0
func requiredHeight(labelText:String) -> CGFloat {
let font = UIFont(name: "Helvetica", size: 16.0)
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: .max))
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.font = font
label.text = labelText
label.sizeToFit()
return label.frame.height
}
有人能理解我嗎?如何獲得value = wordsTotalHeight +(lineNum-1)* lineSpace。此方法返回單詞TotalHeight,但如何獲得lineSpace的值? – ZyusAn