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

2024-02-07

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

当我增加设备的字体大小时,标题字符串不会增加,我已在警报视图控制器中设置了该字符串吗?那么如何使其响应字体大小变化呢?


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

NOTE:如果出现弹出窗口,然后用户在辅助功能设置中更改了字体大小,则此操作将会失败。对于这种情况,您可能需要听UIContentSizeCategory.didChangeNotification https://developer.apple.com/documentation/uikit/uicontentsizecategory/1622948-didchangenotification并在那里更新字体大小。

e.g.

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")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐