【问题标题】:Reduce UIButton label font size for third line减小第三行的 UIButton 标签字体大小
【发布时间】:2013-10-24 14:11:46
【问题描述】:

我有一个可以更改文本的按钮。

如果按钮文本用于第三行,我希望它应该将其字体减少到 minimumScaleFactor。 我正在使用此代码

self.option1Button.titleLabel.minimumScaleFactor = .7;
self.option1Button.titleLabel.numberOfLines = 2;
self.option1Button.titleLabel.adjustsFontSizeToFitWidth = TRUE;

但这不起作用。当文本到达第三行时,它不会改变字体大小。

【问题讨论】:

    标签: iphone objective-c uibutton ios7 uilabel


    【解决方案1】:

    adjustToFit 仅适用于单行标签。

    试试this:

    //Create a string with the text we want to display.
    self.ourText = @"This is your variable-length string. Assign it any way you want!";
    
    /* This is where we define the ideal font that the Label wants to use.
    Use the font you want to use and the largest font size you want to use. */
    UIFont *font = [UIFont fontWithName:@"Marker Felt" size:28];
    
    int i;
    /* Time to calculate the needed font size.
    This for loop starts at the largest font size, and decreases by two point sizes (i=i-2)
    Until it either hits a size that will fit or hits the minimum size we want to allow (i > 10) */
    for(i = 28; i > 10; i=i-2) {
        // Set the new font size.
        font = [font fontWithSize:i];
        // You can log the size you're trying: NSLog(@"Trying size: %u", i);
    
        /* This step is important: We make a constraint box 
        using only the fixed WIDTH of the UILabel. The height will
        be checked later. */ 
        CGSize constraintSize = CGSizeMake(260.0f, MAXFLOAT);
    
        // This step checks how tall the label would be with the desired font.
        CGSize labelSize = [self.ourText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    
        /* Here is where you use the height requirement!
        Set the value in the if statement to the height of your UILabel
        If the label fits into your required height, it will break the loop
        and use that font size. */
        if(labelSize.height <= 180.0f)
            break;
    }
    // You can see what size the function is using by outputting: NSLog(@"Best size is: %u", i);
    
    // Set the UILabel's font to the newly adjusted font.
    msg.font = font;
    
    // Put the text into the UILabel outlet variable.
    msg.text = self.ourText;
    

    【讨论】:

    • 由于某些原因,我在 Interface Builder 中使用 fontSize 和 height 所以这对我来说不起作用。
    • @AzkaarAli 你必须在代码中做一些这样的事情。我认为,界面生成器无法满足您的要求。此外,上面的sizeWithFont 已在 iOS 7 中替换为新功能 (boundingRectWithSize)。
    【解决方案2】:

    如果您希望按钮显示三行,则必须将 numberOfLines 设置为 3。奇怪但确实如此。

    【讨论】:

    • 不,我只想要 2 行,如果文本超过 2 行,它应该减小字体大小以适应 2 行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2014-10-28
    • 2011-12-17
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    相关资源
    最近更新 更多