ios 动态字体

iOS辅助功能允许应用程序适应用户显示设置的变化。动态字体通过preferredFontForTextStyle方法结合多种预置样式使用,以匹配用户的全局设置。当用户更改文本大小时,监听UIContentSizeCategoryDidChangeNotification通知并更新UI。若使用AutoLayout,系统会自动处理布局调整;否则,需手动调用setNeedsLayout重新布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    一直以来,iOS的辅助功能都可以令应用程序与某些能力相配合,并适应很多的限制。用户可以调整显示设置,以影响设备上所安装的全部程序。

    要想在程序中使用动态字体,必须通过preferredFontForTextStyle方法来选中字体,并传入下面几种样式之一:

// Font text styles, semantic descriptions of the intended use for a font returned by +[UIFont preferredFontForTextStyle:]
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleTitle1 NS_AVAILABLE_IOS(9_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleTitle2 NS_AVAILABLE_IOS(9_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleTitle3 NS_AVAILABLE_IOS(9_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleHeadline NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleSubheadline NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleBody NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleCallout NS_AVAILABLE_IOS(9_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleFootnote NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleCaption1 NS_AVAILABLE_IOS(7_0);
UIKIT_EXTERN UIFontTextStyle const UIFontTextStyleCaption2 NS_AVAILABLE_IOS(7_0);

如果我们不直接指定字体名称和大小,而是采用这些预置好的文本样式那么iOS会根据通用设定来选取样式及大小合适的字体。

 为了响应用户对文本大小所做的修改,我们要监听UIContentSizeCategoryDidChangeNotification,并适当的更新UI:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 300, 100)];
    _nameLabel.text = @"动态字体";
    [self.view addSubview:_nameLabel];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preferredContentSizeChanged:) name:UIContentSizeCategoryDidChangeNotification object:nil];
    NSNotification * notice = [NSNotification notificationWithName:UIContentSizeCategoryDidChangeNotification object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice];
}

- (void)preferredContentSizeChanged:(NSNotification *)note
{
    _nameLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleTitle1];
}

    如果使用AutoLayout及标准的UIKit文本元件,那么大部分工作都会由系统自行处理。重置UILabel或UITextView的字体,一般都会使得控件的固有内容尺寸失效,并迫使使他重新布局。但如果开发者是根据frame来手工布局,就需要调用setNeedsLayout来重新布局了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值