gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:42:22 25 4
gpt4 key购买 nike

我有一个使用属性字符串的 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];

尝试

我尝试在设置 attributedText 后调用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com