2017-02-22 71 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") 

}