Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

ios - Problems with getting text from UIAlertView textfield

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)

The alert looks like this:

My alert

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may go with UIAlertController instead of UIAlertView.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...