Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
Amit Raj Avatar asked Jul 08 '15 15:07

Amit Raj


2 Answers

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)
like image 154
pbush25 Avatar answered Oct 14 '22 06:10

pbush25


Swift 5

    let messageString  = "The message to display"
    var myMutableString = NSMutableAttributedString()
    myMutableString = NSMutableAttributedString(string: messageString as String, attributes: [NSAttributedString.Key.font:UIFont(name: "Poppins-medium", size: 14.0)!])
    myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: NSRange(location:0,length:messageString.count))
    alert.setValue(myMutableString, forKey: "attributedMessage")
like image 20
Amal T S Avatar answered Oct 14 '22 06:10

Amal T S