iOS:根据 UILabel 的大小找到正确的字体大小以适合其大小

标签 ios nsstring core-text uifont

我有一个 UILabel,其属性 text 我想使用 NSString 设置文本段落。

我有一个数组,其中存储代表文本段落的字符序列。

该段落不必完全适合/包含在这个 UILabel 中。如果该段落没有结束,我将转到下一个标签。

假设我的 UILabel 的矩形大小为 160 X 240,我如何才能确定正确的字体大小以填充 UILabel 的字符串> 里面很好吗?

是否有一种数学方法可以根据屏幕上矩形的大小来计算字体大小?

例如:

UILabel *aLabel = [[UIlabel alloc] initwithFrame(CGRect){{0, 0}, 160, 240}];
aLabel.font = [UIFont fontWithName:@"Courier New" size:<???>]; //(font unit in points)

NSMutableString *aString = [[NSMutableString alloc] init];

//The following tries to fit the character one by one within the label rect based on   
//the width and height of the UILabel by appending String
int index = 0;
for(int x = 0; x < 240; x+=<???>) //height of label (pixel unit)
{
    for(int y = 0; y < 160; y+=<???>) //width of label (pixel unit)
    {
        [aString appendWithString:[paragraphArray objectAtIndex:index]];
        index++;
    }
    [aString appendWithString:@\n"];  //line break
}
aLabel.text = aString;

我怎样才能确定 ??? 的值?是(即 for 循环的字体大小和像素大小)?

如果这不是执行此类任务的最佳方式,请向我建议其他方式。

最佳答案

+(void)resizeFontForLabel:(UILabel*)aLabel{

    // use font from provided label so we don't lose color, style, etc
    UIFont *font = aLabel.font;

    float lblWidth = aLabel.frame.size.width;
    float lblHeight = aLabel.frame.size.height;

    CGFloat fontSize = [font pointSize];
    UIFont *newFont = font;
    TRC_DBG(@"%@", aLabel.text);
    CGFloat height = [aLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:aLabel.lineBreakMode].height;

    TRC_DBG(@"Label Height %f Constraint height %f", lblHeight, height);
    //Reduce font size while too large, break if no height (empty string)
    while (height > lblHeight && height != 0) {
        fontSize--;
        newFont = [UIFont fontWithName:font.fontName size:fontSize];
        height = [aLabel.text sizeWithFont:newFont constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
        TRC_DBG(@"Constrained Height %f", height);
    };


    TRC_DBG(@"Font size before adjustment %f", aLabel.font.pointSize);
    // Set the UILabel's font to the newly adjusted font.
    aLabel.font = newFont;
    TRC_DBG(@"Adjust to font size of %f", newFont.pointSize);
    [aLabel setNeedsLayout];
}

关于iOS:根据 UILabel 的大小找到正确的字体大小以适合其大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21751738/

相关文章:

objective-c - iOS CoreText : CTFrameSetter is making wider lines than the CGPath allows

ios - 如何在 iOS 上获取本地时间

ios - Xcode 7 - 如何更改构建字符串

iphone - 如何突出显示字符串的NSRange

objective-c - NSString的高效字符处理

objective-c - NSString 没有指定 'assign' 、 'retain' 或 'copy' 属性

ios - 无法将类型 '[AnyObject]' 的值分配给类型 '[UIViewController]?' 的值

ios - Xcode 4.5 中的存档 - 没有错误,但构建已取消

iphone - 在 iOS 中更改 kCTLigatureAttributeName 的值

iphone - 从文本中获取CGPath