let dictTitleColor = [NSAttributedStringKey.foregroundColor: UIColor.LTColor()]
let titleAttributedString = NSMutableAttributedString(string: title, attributes: dictTitleColor)
alert.setValue(titleAttributedString, forKey: "attributedTitle")
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")
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.
e.g.
NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeChanged(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)
The method
@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")
}
Making NSMutableAttributedString
responsive with Dynamic Type
is the same as a simple string element.
I give you an example below that will allow :
Dynamic Type
with a NSMutableAttributedString
.A perfect word truncation with a hyphen using NSMutableParagraphStyle
.
@IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let myFrenchString = "Hello, ceci est un texte anticonstitutionnellement très très long qu'il va falloir couper je nesaisvraimentpasquand."
let paraph = NSMutableParagraphStyle()
paraph.alignment = .justified
paraph.hyphenationFactor = 1.0
let myText = NSMutableAttributedString(string:myFrenchString,
attributes: [
.font: UIFontMetrics(forTextStyle: .title1).scaledFont(for: UIFont(name:"HoeflerText-Black", size:18)!)
])
myText.addAttribute(.paragraphStyle,
value: paraph,
range: NSMakeRange(0,1))
myLabel.attributedText = myText
}
With this snippet, you can make your NSMutableAttributedString
responsive with Dynamic Type
.
I suggest you take a look at this complete and detailed summary of the 2017 WWDC video Building Apps with Dynamic Type if you need further explanation about the Dynamic Type
feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With