如何使 UISegmentedControl 遵循动态类型?

Mar*_*ius 4 accessibility uisegmentedcontrol

我已经开始将动态类型和首选字体应用到我的应用程序中。视图控制器唯一不符合要求的部分是一对分段控制器,当标签等都随着设置中较大的文本滑块扩展时,它们会顽固地保持很小。

Apo*_*eja 5

截至 2018 年 10 月,它似乎UILabel是唯一一个以布尔标志的形式内置可访问性动态更新行为的类adjustsFontForContentSizeCategory。如果将此标志设置为trueUILabel并为标签设置动态类型字体,则标签将根据当前内容大小设置动态调整自身(及其自己的框架)的大小。这也适用于诸如 之类的东西UIButton,它内部用于UILabel显示文本。

不幸的是,对于像 之类的控件UISegmentedControl,似乎没有可以打开或关闭的布尔标志。我是这样实现的:

在您设置视图中viewDidLoadawakeFromNib设置视图之后,您想要注册内容大小更改通知:

NotificationCenter.default.addObserver(self,
                                               selector:#selector(userChangedTextSize(notification:)),
                                               name: UIContentSizeCategory.didChangeNotification,
                                               object: nil)
Run Code Online (Sandbox Code Playgroud)

现在在该userChangedTextSize方法中,您想要重置分段控件上的字体:

 @objc private func userChangedTextSize(notification: Notification) {
    // Replace textStyle with whatever textStyle you want for your segmented control
    segmentedControl.setTitleTextAttributes([
                .font: UIFont.preferredFont(forTextStyle: textStyle)
                ], for: UIControl.State())
}
Run Code Online (Sandbox Code Playgroud)