我有一个使用属性字符串的UILabel
。我希望其行高与字体大小完全相同,而不是大一个像素。但是,正在添加顶部和底部填充。见下图:
这是我创建标签的代码。
NSDictionary *basicAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor], NSBackgroundColorAttributeName: [UIColor blueColor]};
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:basicAttributes];
UIFont *font = [UIFont fontWithName:@"AvenirNext-Regular" size:20.0];
[attributes setObject:font forKey:NSFontAttributeName];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineHeightMultiple = 1.0f;
[attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
self.helloWorldLabel.attributedText = [[NSMutableAttributedString alloc] initWithString:@"Hola" attributes:attributes];
尝试
我尝试在设置属性文本后调用sizeToFit
,但没有成功。
[self.helloWorldLabel sizeToFit];
我尝试过 NSMutableParagraphStyle
的其他属性,例如 lineSpacing
,但没有成功。
paragraphStyle.lineSpacing = 0.0f;
我错过了什么?
提前致谢
最佳答案
听起来您想使用boundingRectWithSize:
这是如何使用它的一个简短示例。此代码将根据标签中的文本动态确定标签尺寸。如果内容需要溢出到多行,则设置约束大小允许最大大小。
NSString *text = [NSString stringWithFormat:@"Title Header:%@", value];
NSRange boldRange = [text rangeOfString:@"Title Header:"];
NSRange normalRange = [text rangeOfString:value];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
//Add attributes for appropriate ranges
[attributedText setAttributes:@{ NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13.0f]} range:boldRange];
[attributedText setAttributes:@{ NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:13.0f]} range:normalRange];
//Determine rect for attributed text constrained within max values
CGRect textAttributedSize = [attributedText boundingRectWithSize:CGSizeMake(CellTitleWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:NULL];
[self.myLabel setText:attributedText];
[self.myLabel setFrame:textAttributedSize];
关于ios - 如何使用 AttributedString 正确设置 UILabel 的行高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23914738/