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/

相关文章:

swift - 无法使用类型为 '[String : AnyObject]' 的索引下标类型为 'NSAttributedStringKey' 的值

ios - 将属性字符串附加到 UITextField 的属性文本并保留其所有以前的颜色和属性

ios - 属性文本中的下划线在 iPhone 6+ 中不起作用

ios - CS193P Cassini 代码在模拟器上运行但在设备上崩溃? "Message from debugger: Terminated due to Memory Error"

iphone - 更改MFMailComposeViewController的标题

ios - 创建一个NSString变量的C宏,变量名作为字符串的内容

ios - 如何在 iOS 应用程序中以编程方式检测 SwiftUI 的使用情况

objective-c - UIModalPresentationFullScreen 在 iPad Landscape 中无法正常工作?

iOS 动画 >> 如何为单个对象设置动画以移动多个位置

javascript - iOS:浏览器因内存不足而崩溃