如何使NSMutableAttributedString响应来自设置应用程序的动态类型文本

Ame*_*mey 6 accessibility nsattributedstring ios swift dynamic-type-feature

let dictTitleColor = [NSAttributedStringKey.foregroundColor: UIColor.LTColor()]
let titleAttributedString = NSMutableAttributedString(string: title, attributes: dictTitleColor)
alert.setValue(titleAttributedString, forKey: "attributedTitle")
Run Code Online (Sandbox Code Playgroud)

当我增加设备的字体大小时标题字符串不增加我在alertview控制器中设置了这个字符串?那么如何使这个响应字体大小更改?

Ind*_*ore 3

let dictTitleColor = [NSAttributedStringKey.foregroundColor : UIColor.green,
                      NSAttributedStringKey.font : UIFont.preferredFont(forTextStyle: .headline)]
let titleAttributedString = NSMutableAttributedString(string: title, attributes: dictTitleColor)
alert.setValue(titleAttributedString, forKey: "attributedTitle")
Run Code Online (Sandbox Code Playgroud)

注意:如果出现弹出窗口,然后用户在辅助功能设置中更改了字体大小,则此操作将会失败。对于这种情况,您可能需要收听UIContentSizeCategory.didChangeNotification并更新那里的字体大小。

例如

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

方法

@objc func preferredContentSizeChanged(_ notification: Notification) {
  let dictTitleColor = [NSAttributedStringKey.foregroundColor : UIColor.green,
                        NSAttributedStringKey.font : UIFont.preferredFont(forTextStyle: .headline)]
  let titleAttributedString = NSMutableAttributedString(string: title, attributes: dictTitleColor)
  alert.setValue(titleAttributedString, forKey: "attributedTitle")
}
Run Code Online (Sandbox Code Playgroud)