我在尝试更改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 :(得分:2)
message
课程中没有关键名称为UIAlertController
的可用属性,在这个位置使用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的标题,那么你应该使用'attributionTitle'键。
你得到了
的输出答案 1 :(得分: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")
}
答案 2 :(得分:0)
您似乎尝试将NSAttributedString设置为String变量message
。试试https://stackoverflow.com/a/42118706/7064692