Set Text Justification in a UIAlertController

Presented is a quick snippet of how to set the text alignment for the message field of a UIAlertControlller. It basically requires creating a NSMutableAttributedString with a NSMutableParagraphStyle that sets the text alignment. The message is then set in the controller by accessing the NSMutableAttributedString object’s string using the “attributedMessage” key.

Here is an example:

// Create the paragraph object with the desired text alignment
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
// Create the string object
let message = NSMutableAttributedString(
    string: """
        Multiline message text...
    attributes: [
        NSAttributedStringKey.paragraphStyle: paragraphStyle,
        NSAttributedStringKey.font : UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
        NSAttributedStringKey.foregroundColor :
// Create the alert controller and add the stylized message string
let alert = UIAlertController(title: "Title", message: "", preferredStyle: UIAlertControllerStyle.alert)        
alert.setValue(message, forKey: "attributedMessage")
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

// Show the alert dialog
self.present(alert, animated: true, completion: nil)

A lot of code just to set the text alignment.

Leave a Reply

Your email address will not be published. Required fields are marked *