Swift UIAlertController获取文本字段文本

时间:2014-10-10 18:41:28

标签: xcode swift uialertcontroller

当按下输入按钮时,我需要从警报视图中的文本字段中获取文本。

func inputMsg() {

    var points = ""
    var outOf = ""

    var alertController = UIAlertController(title: "Input View", message: "Please Input Your Grade", preferredStyle: UIAlertControllerStyle.Alert)

    let actionCancle = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel) { ACTION in

        println("Cacle")
    }
    let actionInput = UIAlertAction(title: "Input", style: UIAlertActionStyle.Default) { ACTION in

        println("Input")
        println(points)
        println(outOf)
    }

    alertController.addAction(actionCancle)
    alertController.addAction(actionInput)
    alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
        txtField.placeholder = "I got"
        txtField.keyboardType = UIKeyboardType.NumberPad
        points = txtField.text
        })



    alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
        txtField.placeholder = "Out Of"
        txtField.keyboardType = UIKeyboardType.NumberPad
        outOf = txtField.text
    })
    presentViewController(alertController, animated: true, completion: nil)
}

2 个答案:

答案 0 :(得分:8)

请求这里是一个实施解决方案。

alertController.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default,handler: {
            (alert: UIAlertAction!) in
            if let textField = alertController.textFields?.first as? UITextField{
                println(textField.text)
            }
        }))

如上所述,alertController有一个名为textFields的属性。如果添加了文本字段,则可以有条件地解包该属性以安全地访问文本字段。在这种情况下,由于只有一个文本字段,我只是使用first属性进行解包。希望它有所帮助。

答案 1 :(得分:3)

UIAlertController具有textFields属性。这是它的文本字段。您的任何处理程序都可以检查它,从而可以从任何文本字段中获取文本。