I have successfully used the following, for both aligning and styling the text of UIAlertControllers:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Left
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleBody),
NSForegroundColorAttributeName : UIColor.blackColor()
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
You can do a similar thing with the title, if you use "attributedTitle"
, instead of "attributedMessage"
Swift 3 update
The above still works in Swift 3, but the code has to be slightly altered to this:
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName : UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
NSForegroundColorAttributeName : UIColor.black
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
Swift 4 update
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSAttributedStringKey.paragraphStyle: paragraphStyle,
NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
NSAttributedStringKey.foregroundColor: UIColor.black
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
Swift 5 update
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
let messageText = NSAttributedString(
string: "message",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.foregroundColor : UIColor.primaryText,
NSAttributedString.Key.font : UIFont(name: "name", size: size)
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…