如果选择了CollectionViewCell,则弹出警报

时间:2017-06-14 05:45:57

标签: ios swift xcode

有一个带有几个项目的CollectionView。我正在尝试使用textfield弹出警告消息,以便在选择项目时创建新文件。

但是,当执行最后一条指令(self.present(....))时,会出现一条错误消息:"致命错误:在解开一个Optional值时意外发现nil"发生。

我也试过了代码  :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) 最后弹出警报框。

3 个答案:

答案 0 :(得分:2)

我建议你使用委托。我会向你演示一些代码。 首先创建原型

protocol AlertViewDelegate {
      func alertSending(sender: UIAlertController)
}

比你在uicollectionviewcell类中实现

var delegate: AlertViewDelegate?
func actionMethod() { 
     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)
     delegate?.alertSending(sender: alert)
}

最后你转到你的uicollectionviewcontroller类而不是扩展委托

extension ViewCollectionViewController: AlertViewDelegate {
func alertSending(sender: UIAlertController) {
    self.present(sender, animated: true, completion: nil)        
}

问题请评论。希望对你有效。享受!

答案 1 :(得分:0)

你在这两行中遇到了问题:

let fileName = (alert.textFields?.first)! as UITextField
print(fileName.text)

将它们更改为以下行:

let fileName = alert.textFields?.first?.text
print(fileName!)

答案 2 :(得分:0)

仅将部分替换为createAction

let createAction = UIAlertAction(title: "Create" ,style: .default){
     (action:UIAlertAction!) -> Void in
     guard let textField = alert.textFields?.first,
         let fileName = textField.text else { return }
         print(fileName)
}
alert.addAction(createAction)