场景
- 弹出的卡片View,有多个
UILabel
,每个UILabel
可能有1~2行文字
- 除了
UILabel
还有UIImageView
、UIButton
等控件
- 根据UI提供的sketch中相邻UI控件的高度(
cur.top = last.bottom + distance
)最后可以得出整个卡片view的height
- 因此需要根据文字动态的调整
UILabel
的行高
方法
- 如果是NSString,使用
- (CGRect)boundingRectWithSize: options: attributes: context:
,attributes
中要指定和动态高度有关的参数值,比如NSParagraphStyleAttributeName
、NSFontAttributeName
等
-(UILabel *)tipLabel {
if (!_tipLabel) {
_tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, MAXFLOAT)];
_tipLabel.text = @"这是第一行\n这是第二行";
_tipLabel.font = kMediumFontOfSize(20);
_tipLabel.textAlignment = NSTextAlignmentCenter;
_tipLabel.textColor = kColorWhite;
NSMutableAttributedString *customText = [[NSMutableAttributedString alloc] initWithString:_tipLabel.text];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 5;
style.alignment = _tipLabel.textAlignment;
NSRange customRange = NSMakeRange(0, customText.length);
[customText addAttribute:NSKernAttributeName value:@(0.64f) range:customRange]<