gpt4 book ai didi

ios - 自动缩小后如何获取 UILabel 中文本的磅值

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

我有一个 UILabel,其中的文本会自动缩小以适合。一旦发生这种情况,我需要知道生成的字体的点大小,以便我可以在其他地方的另一个标签中设置完全相同的大小。

如果我访问 label.font.pointSize,我会返回原始大小,而不是缩小后的大小。所以我然后尝试使用这个 NSString 添加来计算字体大小:

- (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

但是,这对我也不起作用,因为如果不考虑标签的高度限制,只考虑其宽度。 (在我的例子中,字体需要进一步缩小以适应框架的高度)。

这似乎只给我留下了一个绝对可怕的选择,那就是重复调用以下函数,直到找到真正适合框架的最大高度:

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

显然,这将是非常低效和令人讨厌的。

有没有人有更好的解决方案?

蒂姆

最佳答案

好吧,在没有人能为我提供更好的选择的情况下,我想我会分享我编写的一个类别来以困难的方式解决问题。

但是,如果有一种直接的方法来访问 UILabel 的缩小字体大小,那显然是理想的...

事不宜迟,此函数将返回适合约束大小的自动缩小字体大小。

接口(interface):

 @interface NSString (FontSize)

- (CGSize)sizeWithFont:(UIFont *)font
minFontSize:(CGFloat)minFontSize
actualFontSize:(CGFloat *)actualFontSize
constrainedToSize:(CGSize)maxSize
lineBreakMode:(UILineBreakMode)lineBreakMode;

@end

实现:

@implementation NSString (FontSize)

- (CGSize)sizeWithFont:(UIFont *)font
minFontSize:(CGFloat)minFontSize
actualFontSize:(CGFloat *)actualFontSize
constrainedToSize:(CGSize)maxSize
lineBreakMode:(UILineBreakMode)lineBreakMode
{
CGFloat size;
CGSize boundingBox;

// First, get the OS to fit the text into the width

boundingBox = [self sizeWithFont:font
minFontSize:minFontSize
actualFontSize:&size
forWidth:maxSize.width
lineBreakMode:lineBreakMode];

// Return here if the min size has already been reached

if (size <= minFontSize)
{
*actualFontSize = size;
return boundingBox;
}

// Binary search biggest size that will fit within the height of the box

CGFloat upperBound = size;
CGFloat lowerBound = minFontSize;

UIFont *f;
CGFloat fontSize;
while (upperBound > lowerBound + 0.5) {

fontSize = (upperBound + lowerBound) / 2;

f = [UIFont fontWithName:font.fontName size:fontSize];
boundingBox = [self sizeWithFont:f];

if (boundingBox.height > maxSize.height)
upperBound = fontSize - 0.5;
else
lowerBound = fontSize;
}

// Return the result

*actualFontSize = fontSize;
return boundingBox;
}

@end

关于ios - 自动缩小后如何获取 UILabel 中文本的磅值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12705822/

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