【问题标题】:Shrink text inside UIlabel programmatically以编程方式缩小 UIlabel 内的文本
【发布时间】:2013-01-07 01:08:35
【问题描述】:

我正在尝试缩小 UILabel 中的文本。我的文本是一个字符串,我最多有 7 行,有时还不够,然后我需要缩小文本以适应这 7 行。这是我的代码。`

// create label
    UILabel *desc = [[UILabel alloc] initWithFrame:CGRectMake(5, 220, 310, 200)];
    desc.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1];
    desc.font = [UIFont fontWithName:@"Helvetica" size:30];
    desc.numberOfLines = 7;
    desc.textColor = [UIColor blackColor];
    desc.layer.borderColor = [UIColor blackColor].CGColor;
    desc.layer.borderWidth = 1.0;
    desc.text = // MY string ;
    desc.adjustsFontSizeToFitWidth = YES;
    [self.view addSubview:desc];`

我什至试过[desc sizeToFit]

我无法弄清楚我做错了什么。我已经检查了所有关于此的帖子。

感谢您的帮助

【问题讨论】:

    标签: iphone uilabel xcode4.5


    【解决方案1】:

    您可以使用辅助函数来调整它的大小。 Here 就是一个例子。我只是将 lineBreakMode 更改为 NSLineBreakByWordWrapping(因为以前在 iOS6 中已弃用)。

    + (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize
    {
        // use font from provided label so we don't lose color, style, etc
        UIFont *font = aLabel.font;
    
        // start with maxSize and keep reducing until it doesn't clip
        for(int i = maxSize; i > 10; i--) {
            font = [font fontWithSize:i];
            CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT);
    
            // This step checks how tall the label would be with the desired font.
            CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
            if(labelSize.height <= aLabel.frame.size.height)
                break;
        }
        // Set the UILabel's font to the newly adjusted font.
        aLabel.font = font;
    }
    

    【讨论】:

      【解决方案2】:

      据我所知,UILabel 不支持在多行模式下自动计算字体大小。您可以迭代字体大小,直到它适合。

      也看看

      sizeWithFont:forWidth:lineBreakMode:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-17
        • 2011-11-06
        • 2013-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多