一直以来,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来重新布局了。