从UIAlertView文本字段获取文本的问题 [英] Problems with getting text from UIAlertView textfield

查看:176
本文介绍了从UIAlertView文本字段获取文本的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my application I want a alert with a textfield. After clicking on "Done" I want to save the textfield input in a String. After clicking on "Cancel" I want only to close the alert. I've created my alert like this:

    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)

警报如下所示:

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

I want to know how to get the text from the textfield, and how to create events for the "Done" button and the "Cancel" button.

推荐答案

您可以使用UIAlertController而不是UIAlertView。

You may go with UIAlertController instead of UIAlertView.

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

I've already implemented and tested too using UIAlertController for what you actually want. Please try the following code

    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")
    })

这篇关于从UIAlertView文本字段获取文本的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆