简体   繁体   English

使用自动布局更改UILabel的字体

[英]Change font of UILabel with autolayout

Normally, you use: 通常,您使用:

label.adjustsFontSizeToFitWidth = YES;

to make a label reduce the size of its font whenever it is no longer possible to increase the size of its frame. 使标签在不再可能增加其框架大小时减小其字体大小。

Is there any way to make it try an alternate font, like a condensed version of the same font family before it reduces font size? 有没有办法让它尝试其他字体,例如在减小字体大小之前,该字体家族的精简版本?

There are a few good ways to handle this. 有几种很好的方法可以解决此问题。 In IB select your label: 在IB中,选择您的标签:

Method 1: 方法1:

在此处输入图片说明

If you click the plus button, you can add specific fonts for a given size class. 如果单击加号按钮,则可以为给定的尺寸类别添加特定的字体。

In code: 在代码中:

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
{
    if(self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassRegular && self.view.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular)
    {
        //iPad here
        myLbl.Font = [UIFont fontWithName:@"Heyo" size:10];
    }
}

The better way, in my opinion, is Method 2: 我认为更好的方法是方法2:

在此处输入图片说明

With this approach, you can either tell the font to shrink up to a certain size, or instead identify a scale factor. 使用这种方法,您可以告诉字体缩小到一定大小,或者标识比例因子。 Toy with these values until you get the desired result. 玩弄这些值,直到获得所需的结果。 I also talk about this topic in this tutorial . 我还将在本教程中讨论这个主题。

In code: 在代码中:

//Minimum font size
[myLbl setMinimumScaleFactor:MIN_FONT_SIZE/[UIFont labelFontSize]];

//Scale factor
[myLbl setMinimumScaleFactor:0.4];

This didn't work for me, but this did. 这对我不起作用,但确实如此。 You also need to use the system font in IB 您还需要在IB中使用系统字体

#import <UIKit/UIKit.h>

@interface UILabelEx : UILabel


@end

#import "UILabelEx.h"
#import "Constants.h"

@implementation UILabelEx

- (void) traitCollectionDidChange: (UITraitCollection *) previousTraitCollection {
    [super traitCollectionDidChange: previousTraitCollection];

    self.font = [UIFont fontWithName:APP_FONT size:self.font.pointSize];   
}
@end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM