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

问题描述:

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

当我增加设备的字体大小时,标题字符串没有增加,我已经在Alertview控制器中设置了此字符串?那么如何使它对字体大小变化做出响应?

When I Increase the font size of the device the title string dont increase i have set this string in alertview controller ? So How to make This Responsive to font size Change ?

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

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

NOTE: This will fail if the popup is presented and then user changed the font size in the accessibility settings. For this case you might need to listen to the UIContentSizeCategory.didChangeNotification and update the font size there.

例如

NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeChanged(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)

方法

@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")
}