2017-02-22 53 views
1

我得到下时试图改变文字颜色描述错误的UIAlertController内:应用程序崩溃,迅速

终止应用程序由于未捕获的异常 “NSInvalidArgumentException”的,原因是: ' - [NSConcreteAttributedString rangeOfCharacterFromSet:]:无法识别的选择发送到实例 0x60000003e320'

功能试图更改的颜色:

@objc private func submitScore(color: Bool = false) { 
    var mess = "" 
    mess = color ? "Invalid username" : "" 
    let alertController = UIAlertController.init(title: "Submit score", message: mess, preferredStyle: .alert) 
    alertController.setValue(NSAttributedString(string: mess, attributes: [NSForegroundColorAttributeName: UIColor.red]), forKey: "message") 


    //Submit button calls function again 
    let submit = UIAlertAction(title: "Submit", style: .default) { (submit) in 
     self.submitScore(color: true) 
    } 
    let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: { (cancel) in 

    }) 
    alertController.addTextField(configurationHandler: {(textfield) in 
     textfield.placeholder = "Nickname" 
    }) 
    alertController.addAction(submit) 
    alertController.addAction(cancel) 

    present(alertController, animated: true, completion: {(alertController) in 
     print("shown") 
    }) 
} 

如果我删除线5 NSForegroundColorAttributeName是有效NSAttributedString属性,所以我不明白错误的问题就解决了..

+0

属性'message'是类型的输出'String'所以你不能任何属性添加到它。没有设置属性信息的暴露属性。 – rckoenes

回答

2

没有可用密钥名的属性是UIAlertControllermessage,在这个地方使用attributedMessage改变的消息。

在这个地方

let alertController = UIAlertController.init(title: "Submit score", message: mess, preferredStyle: .alert) 
    alertController.setValue(NSAttributedString(string: mess, attributes: [NSForegroundColorAttributeName: UIColor.red]), forKey: "message") 

使用

let alertController = UIAlertController.init(title: "Submit score", message: mess, preferredStyle: .alert) 
alertController.setValue(NSAttributedString(string: mess, attributes: [NSForegroundColorAttributeName: UIColor.red]), forKey: "attributedMessage") 

,如果你想改变UIAlertController的称号,那么你应该使用 'attributedTitle' 键。

你的

enter image description here

+0

感谢它的工作! :) –

0
@objc private func submitScore(color: Bool = false) { 
    var mess = "" 
    mess = color ? "Invalid username" : "" 
    let alertController = UIAlertController.init(title: "Submit score", message: mess, preferredStyle: .alert) 

    //Submit button calls function again 
    let submit = UIAlertAction(title: "Submit", style: .default) { (submit) in 
     self.submitScore(color: true) 
    } 
    let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: { (cancel) in 

    }) 
    alertController.addTextField(configurationHandler: {(textfield) in 
     textfield.placeholder = "Nickname" 
    }) 
    alertController.addAction(submit) 
    alertController.addAction(cancel) 

    present(alertController, animated: true, completion: {(alertController) in 
     print("shown") 
    }) 

    alertController.setValue(NSAttributedString(string: mess, attributes: [NSForegroundColorAttributeName: UIColor.red]), forKey: "message") 

}