Search code examples
swiftuicoloruialertcontroller

Change the color of the message UIAlertController in Swift


I want to change the color of message in UIAlertController in swift. The default is black I want to change it red.

My UIAlertController looks like follows:

alert = UIAlertController(title: "", message: "Invalid Name", preferredStyle: UIAlertControllerStyle.Alert)
alert.view.tintColor = UIColor.blackColor()
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
}))
self.presentViewController(alert, animated: true, completion: {
    println("completion block")
})

I want to change the color of Invalid Name in the above alert box.


Solution

  • You can use attributedStrings to create the color, font, size, and style that you want, and then set the string as the title.

    EDIT: Updated with example

    let attributedString = NSAttributedString(string: "Invalid Name", attributes: [
      NSParagraphStyleAttributeName: paragraphStyle,
      NSFontAttributeName : UIFont.systemFontOfSize(15),
      NSForegroundColorAttributeName : UIColor.redColor()
    ])
    let alert = UIAlertController(title: "Title", message: "", preferredStyle: .Alert)
    
    alert.setValue(attributedString, forKey: "attributedMessage")
    
    let cancelAction = UIAlertAction(title: "Cancel",
        style: .Default) { (action: UIAlertAction!) -> Void in
    }
    
    presentViewController(alert,
        animated: true,
        completion: nil)