Is there a way to change the alignment of the message displayed inside a UIAlertController on iOS 8?
I believe accessing the subviews and changing it for the UILabel
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"
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")
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")
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")
Swift 4.2 + multiline string linebreak indentation
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.headIndent = 14
let messageText = NSMutableAttributedString(
string: "... multiline string need linebreak indentation ...",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),
NSAttributedString.Key.foregroundColor: UIColor.gray
]
)
alert.setValue(messageText, forKey: "attributedMessage")