如何在Swift中为UIAlertAciton设置自定义字体

时间:2017-05-26 07:10:29

标签: ios swift uialertcontroller uialertaction

 let alertcontroller = UIAlertController(title: "try", message: "now", preferredStyle: .alert)
let action = UIAlertAction(title: "Some title", style: .destructive, handler: nil)
    let attributedText = NSMutableAttributedString(string: "New User")

    let range = NSRange(location: 0, length: attributedText.length)
    attributedText.addAttribute(NSKernAttributeName, value: 1.5, range: range)
    attributedText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 25.0), range: range)
    action.setValue(UIColor(hex: 0xFF9B05),forKey: "titleTextColor")
    alertcontroller.addAction(action)

1 个答案:

答案 0 :(得分:1)

参考表格:Refer from Here.

代码:

let alertController = UIAlertController(title: "Alert Title", message: "This is testing message.", preferredStyle: UIAlertControllerStyle.Alert)
    // Background color.
    let backView = alertController.view.subviews.last?.subviews.last
    backView?.layer.cornerRadius = 10.0
    backView?.backgroundColor = UIColor.yellowColor()

    // Change Title With Color and Font:

    let myString  = "Alert Title"
    var myMutableString = NSMutableAttributedString()
    myMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:0,length:myString.characters.count))
    alertController.setValue(myMutableString, forKey: "attributedTitle")

    // Change Message With Color and Font

    let message  = "This is testing message."
    var messageMutableString = NSMutableAttributedString()
    messageMutableString = NSMutableAttributedString(string: message as String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    messageMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:0,length:message.characters.count))
    alertController.setValue(messageMutableString, forKey: "attributedMessage")


    // Action.
    let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
    action.setValue(UIColor.orangeColor(), forKey: "titleTextColor")
    alertController.addAction(action)
    self.presentViewController(alertController, animated: true, completion: nil)

输出:

enter image description here