UIAlertController文本字段未获取输入

时间:2019-03-26 02:10:56

标签: ios swift

我正在尝试编码,一个UIAlertController通过UITextfield从用户那里得到输入。

当我运行打印语句时,在文本字段中键入内容并单击保存按钮后,什么也不会打印。

@IBAction func reqTimeButton(_ sender: Any) {

  // time is requested by student

    timer.invalidate()

    let alert = UIAlertController(title: "Time Request", message: "Please enter your reason to extend the time of your trip", preferredStyle: .alert)

    alert.addTextField { (reason) in

        reason.placeholder = "" }

    alert.addAction(UIAlertAction(title: "Continue", style: .default, handler: { (action) in

        let textField = alert.textFields![0]
        textField.text = self.request
        self.totalTime = self.totalTime + 480
        self.initialTime = self.initialTime + 480
        self.runTimer()
        print(textField.text!)   }))

    alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in

        self.runTimer()  }))

    self.present(alert, animated: true, completion: nil)        
}

2 个答案:

答案 0 :(得分:0)

使用此代码从UITextField获取文本,希望对您有所帮助。

let alertController = UIAlertController(title: "Time Request", message: "Please enter your reason to extend the time of your trip", preferredStyle: .alert)
alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "Enter your reason"
}
alertController.addAction(UIAlertAction(title: "Continue", style: .default, handler: { (okAction) in
       let textField = alertController.textFields![0] as UITextField
       print(textField)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)

答案 1 :(得分:0)

我弄清楚出了什么问题。这是工作代码。

@IBAction func reqTimeButton(_ sender:Any){

  // time is requested by student

    timer.invalidate()

    let alert = UIAlertController(title: "Time Request", message: "Please enter your reason to extend the time of your trip", preferredStyle: .alert)

    alert.addTextField { (reason) in

        reason.placeholder = "" }

    alert.addAction(UIAlertAction(title: "Continue", style: .default, handler: { (action) in

        let textField = alert.textFields![0]
        print(textField.text!)
        self.totalTime = self.totalTime + 480
        self.initialTime = self.initialTime + 480
        self.runTimer()
        self.request = textField.text!
        print(self.request)  }))

    alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in

        self.runTimer()  }))

    self.present(alert, animated: true, completion: nil)        
}