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.
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With