在Swift中更改消息UIAlertController的颜色

问题描述 投票:2回答:2

我想在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")
})

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

swift uicolor uialertcontroller
2个回答
17
投票

您可以使用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)

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")
© www.soinside.com 2019 - 2024. All rights reserved.