在Swift中更改消息UIAlertController的颜色

时间:2015-07-08 15:00:04

标签: swift uicolor uialertcontroller

我想在swift中更改UIAlertController中的消息颜色。默认为黑色我想将其更改为红色。

我的UIAlertController如下所示:

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")
})

我想在上面的提醒框中更改无效名称的颜色。

2 个答案:

答案 0 :(得分:15)

您可以使用attributedStrings创建所需的颜色,字体,大小和样式,然后将字符串设置为标题。

编辑:更新了示例

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)

答案 1 :(得分:0)

快速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.primaryColor(), range: NSRange(location:0,length:messageString.count))
    alert.setValue(myMutableString, forKey: "attributedMessage")