ios - 如何使用 AttributedString 正确设置 UILabel 的行高?

标签 ios objective-c nsattributedstring

我有一个使用属性字符串的UILabel。我希望其行高与字体大小完全相同,而不是大一个像素。但是,正在添加顶部和底部填充。见下图:

enter image description here

这是我创建标签的代码。

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/

相关文章:

ios - 使用 Codable 解析 JSON 响应会 swift 出错

ios - 如何使用 UIAutomation 测试是否从我的应用程序打开了链接?

iPhone - 使用 Sharekit 将图像发送到 Facebook

ios - 如何在 SWIFT Xcode 中导入 Rollout.io

ios - Swift 2 迁移问题

IOS UICollectionView 和 UIScrollView 回收问题

c++ - Objective C "@property (nonatomic, retain)"的 C++ 等价物是什么?

swift - NSAttributedString 与 Swift 2.1 中的属性

ios7 - UILabel 和 NSLinkAttributeName : Link is not clickable

iphone - iPhone 中的高级搜索实现?