gpt4 book ai didi

ios - 获取带字体的字符串的高度

转载 作者:行者123 更新时间:2023-11-29 02:52:26 24 4
gpt4 key购买 nike

我很难搞清楚如何获取包含指定文本和使用指定字体的 UILabel 的大小,特别是高度。基本上,我想要一个返回给定字符串和字体高度的方法。

这是我目前所拥有的:

+ (CGFloat)heightForString:(NSString *)string withFontSize:(CGFloat)size
{
NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:size]};

NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:string
attributes:attributes];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;

CGRect paragraphRect =
[attributedText boundingRectWithSize:CGSizeMake(screenWidth, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];

return paragraphRect.size.height;
}

返回的高度大约是应有的一半。我知道这个问题已被问过一百万次,但没有一个解决方案完全有效。

最佳答案

使用此类别计算给定字体和最大宽度的文本高度,用于 SOMessaging

基本上我用它来替代 iOS6 的 sizeWithFont:constrainedToSize:lineBreakMode 方法

关于ios - 获取带字体的字符串的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24342272/

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