有一个CollectionView和一些项目。我试图弹出一个警告消息与文本字段来创建一个新文件时,该项目被选中。如果选择了CollectionViewCell,那么Pop Alert
但是,当执行最后一条指令(self.present(....))时,会出现错误消息:“致命错误:在解包可选值时意外发现零”。
我也尝试了 的代码:How to present an AlertView from a UICollectionViewCell 但它不起作用。
self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
有没有可能这样做?我怎么解决这个问题?谢谢。
func addFile(){
let alert = UIAlertController(title: "New file name:", message: "", preferredStyle: .alert)
alert.addTextField{
(textField: UITextField!) -> Void in
textField.placeholder=""
}
let cancelAction = UIAlertAction(title: "Cancel",style: .cancel, handler: nil)
alert.addAction(cancelAction)
let createAction = UIAlertAction(title: "Create" ,style: .default){
(action:UIAlertAction!) -> Void in
let fileName = (alert.textFields?.first)! as UITextField
print(fileName.text)
}
alert.addAction(createAction)
self.present(alert, animated: true, completion: nil)
}
编辑:解决。
我修改了最后一行为 UIApplication.shared.keyWindow?.rootViewController?.presentedViewController?.present(alert,animated: true, completion: nil)
最后弹出提示框。
部分在哪一行,你是专门得到的错误? – nayem
它停在“self.present(alert,animated:true,completion:nil) – szeto1121