从UIAlertView文本字段获取文本的问题

Pas*_*ann 6 alert textfield uialertview ios swift

在我的应用程序中,我想要一个带文本字段的警报.单击"完成"后,我想将文本字段输入保存在字符串中.点击"取消"后,我只想关闭提醒.我已经创建了这样的警报:

    var alert = UIAlertView()
    alert.title = "Enter Input"
    alert.addButtonWithTitle("Done")
    alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
    alert.addButtonWithTitle("Cancel")
    alert.show()

    let textField = alert.textFieldAtIndex(0)
    textField!.placeholder = "Enter an Item"
    println(textField!.text)
Run Code Online (Sandbox Code Playgroud)

警报看起来像这样:

我的警觉

我想知道如何从文本字段中获取文本,以及如何为"完成"按钮和"取消"按钮创建事件.

iRi*_*iya 28

您可以使用UIAlertController而不是UIAlertView.

我已经使用UIAlertController实现并测试了你真正想要的东西.请尝试以下代码

    var tField: UITextField!

    func configurationTextField(textField: UITextField!)
    {
        print("generating the TextField")
        textField.placeholder = "Enter an item"
        tField = textField
    }

    func handleCancel(alertView: UIAlertAction!)
    {
        print("Cancelled !!")
    }

    var alert = UIAlertController(title: "Enter Input", message: "", preferredStyle: .Alert)

    alert.addTextFieldWithConfigurationHandler(configurationTextField)
    alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:handleCancel))
    alert.addAction(UIAlertAction(title: "Done", style: .Default, handler:{ (UIAlertAction) in
        print("Done !!")

        print("Item : \(self.tField.text)")
    }))
    self.presentViewController(alert, animated: true, completion: {
        print("completion block")
    })
Run Code Online (Sandbox Code Playgroud)

  • @DharmeshKheni很高兴它帮助了你! (2认同)