【问题标题】:Getting text with UITextField Popup Alertview with Swift 3 fatal error使用 Swift 3 致命错误使用 UITextField Popup Alertview 获取文本
【发布时间】:2016-11-26 13:36:17
【问题描述】:

我有弹出警报并使用 UITextField 代码获取文本,但是当我想获取文本字符串时,我会出现 nil 错误。我的代码在这里。我正在使用最新的 Xcode 和 Swift 3。

   var tField: UITextField!


   @IBAction func addcommentButtonTapped(sender: AnyObject) {


    let alert = UIAlertController(title: "Write Comment", message: "", preferredStyle: UIAlertControllerStyle.alert)

    alert.addTextField { (configurationTextField) in

    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:self.handleCancel))
    alert.addAction(UIAlertAction(title: "Send", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
    print("Done !!")


       let textField = self.tField.text // HERE GIVES ERROR nil = tField


        if  textField != nil {
              print("Item : \(textField))")
        }



    }))
    self.present(alert, animated: true, completion: {
    print("completion block")
    })

    }

    }

错误

致命错误:在展开可选值时意外发现 nil

错误行

let textField = self.tField.text // 这里给出错误 nil = tField

谢谢!

【问题讨论】:

  • 你有没有给self.tField分配过东西?

标签: ios uitextfield swift3


【解决方案1】:

您已经在addTextField 闭包中添加了您的alertaction,您还需要使用alertController 的textFields 数组中的第一个textField,因此您需要像这样更改您的代码

@IBAction func addcommentButtonTapped(sender: AnyObject) {

   let alert = UIAlertController(title: "Write Comment", message: "", preferredStyle: UIAlertControllerStyle.alert)
   alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:self.handleCancel))
   alert.addTextField { (configurationTextField) in
       //configure here your textfield
       configurationTextField.textColor = UIColor.greenColor()
   }
   alert.addAction(UIAlertAction(title: "Send", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
       print("Done !!")
       if let textField = alert.textFields?.first {
           print("Item : \(textField.text))")
       }
   }))
   self.present(alert, animated: true, completion: {
       print("completion block")
   })    
}

【讨论】:

  • 欢迎朋友快乐编码:)
  • 0 否决票不应该只是:让 textField = alert.textFields?.first 作为 UITextField 的向下转换吗?只解开可选项?
  • @TaichiKato 编辑了答案并解开了可选内容。
  • 谢谢,代码运行良好,我只是想让您知道,这样查看此代码的人就不会遇到同样的问题。
猜你喜欢
  • 2015-02-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 2018-11-03
  • 2016-10-09
  • 2016-01-12
  • 2016-03-13
  • 2018-05-13
相关资源
最近更新 更多