49

I have this code, but I dont know how to show a textfield inside the UIAlertView.

var altMessage = UIAlertController(title: "Warning", message: "This is Alert Message", preferredStyle: UIAlertControllerStyle.Alert)
altMessage.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(altMessage, animated: true, completion: nil)

I have this code for textfield , how can I show this in UIAlerView

var my:UITextField = UITextField(frame: CGRectMake(0, 0, 10, 10))

I also tried this code:

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

When I specify the AlertStyle plainText, it shows a TextField with default placeholder, "Login".. I want to change that, I want to show a Keyboard of Decimal Pad. I also want to handle the value the user enters into the textField. Can someone help me with this?

Stonz2
  • 6,306
  • 4
  • 44
  • 64
Apple Kid
  • 623
  • 2
  • 7
  • 16

10 Answers10

37

You can access the textfield with:

let textField = alert.textFieldAtIndex(0)

Then to change the placeholder text:

textField.placeholder = "Foo!"

And the keyboard type:

textField.keyboardType = ...
AstroCB
  • 12,337
  • 20
  • 57
  • 73
David Berry
  • 40,941
  • 12
  • 84
  • 95
  • OK, I got it. But how can i add the textField to AlertView,>? – Apple Kid Jun 07 '14 at 04:33
  • You got that part already, set the `alertViewStyle` to one of the `TextInput` variants. You can only have zero-two text fields in an alert, if you want more than that you'll have to roll your own. – David Berry Jun 07 '14 at 04:34
  • OKay, That was Awesome...!! How can i handle the TexttInput .?? – Apple Kid Jun 07 '14 at 04:37
  • `alert.textFieldAtIndex(0).text` is the text in the first field. – David Berry Jun 07 '14 at 04:38
  • 2
    That i know, I was asking how can i handle with these buttons, I want to return the value when the user clicks "Done" button.?? – Apple Kid Jun 07 '14 at 04:41
  • I'd suggest checking out the UIAlertView reference page. Maybe google for some alert view tutorials. Fundamentally it's the same as for Objective-C. – David Berry Jun 07 '14 at 04:42
  • Hello, the thing is that.. we have to add the UIAlertViewDelegate and add the methods to it. When i try to add it not showing up.. the AlertView Delegate Methods – Apple Kid Jun 07 '14 at 04:48
23

Try This Code (with swift):

func configurationTextField(textField: UITextField!)
    {
        println("configurat hire the TextField")

        if let tField = textField {

            self.textField = textField!        //Save reference to the UITextField
            self.textField.text = "Hello world"
        }
    }


 func handleCancel(alertView: UIAlertAction!)
        {
           println("User click Cancel button") 
           println(self.textField.text)
        }

 var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.Alert)

    alert.addTextFieldWithConfigurationHandler(configurationTextField)

    alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:handleCancel))
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
            println("User click Ok button")
            println(self.textField.text)
        }))
    self.presentViewController(alert, animated: true, completion: {
            println("completion block")
        })

Can you see also my answer here

Community
  • 1
  • 1
Guy Kahlon
  • 4,510
  • 4
  • 30
  • 41
16

In Objective C

 UIAlertView *alertView =  [[UIAlertView alloc]initWithTitle:@"Duplicate file" message:@"A file with the same name already exists." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
 alertView.alertViewStyle = UIAlertViewStylePlainTextInput;

 [[alertView textFieldAtIndex:0] setText:@"Filename"];
 [[alertView textFieldAtIndex:0] setPlaceholder:@"Enter Filename"];
 [alertView show];

In Swift 2.3

func doSomething(){
    var alert = UIAlertController(title: "Duplicate file", message: "A file with the same name already exists.", preferredStyle: UIAlertControllerStyle.Alert)

    alert.addTextFieldWithConfigurationHandler(configurationTextField)

    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
         print("User click Ok button")
         print(self.textField.text)
    }))

 self.presentViewController(alert, animated: true, completion: {
     print("completion block")
 })
}

 func configurationTextField(textField: UITextField!){
     textField.text = "Filename"
 }

In Swift 3

func doSomething(){
    var alert = UIAlertController(title: "Duplicate file", message: "A file with the same name already exists.", preferredStyle: UIAlertControllerStyle.alert)

    alert.addTextField(configurationHandler: configurationTextField)

    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
        print("User click Ok button")
        print(self.textField.text)
    }))

    self.present(alert, animated: true, completion: {
        print("completion block")
    })
}

func configurationTextField(textField: UITextField!){
    textField.text = "Filename"
}
Alessandro Garcez
  • 728
  • 2
  • 6
  • 25
Darshit Shah
  • 2,366
  • 26
  • 33
14

Swift 5

public func alertWithTextField(title: String? = nil, message: String? = nil, placeholder: String? = nil, completion: @escaping ((String) -> Void) = { _ in }) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addTextField() { newTextField in
        newTextField.placeholder = placeholder
    }
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completion("") })
    alert.addAction(UIAlertAction(title: "Ok", style: .default) { action in
        if
            let textFields = alert.textFields,
            let tf = textFields.first,
            let result = tf.text
        { completion(result) } 
        else
        { completion("") }
    })
    navigationController?.present(alert, animated: true)
}

Usage:

alertWithTextField(title: "bork", message: "borkborkbork", placeholder: "bork?") { result in
    print(result)
}
Jimmy_m
  • 1,568
  • 20
  • 24
  • Fatal error: NavigationController can't present . Only subclasses of NavigationController are allowed.: file /Users/tamim/Projects/chatmio-ios/Display/Display/NavigationController.swift, line 1020 – Tamim Attafi Apr 24 '20 at 06:17
  • @TamimAttafi Replace `navigationController` with `self` if you're not using this code inside an `UINavigationController` – AnthoPak Feb 02 '22 at 16:17
13
            var inputTextField: UITextField?

            //Create the AlertController
            let actionSheetController: UIAlertController = UIAlertController(title: "Rename", message: "", preferredStyle: .Alert)

            //Create and add the Cancel action
            let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
        //Do some stuff
            }
            actionSheetController.addAction(cancelAction)
            //Create and an option action
            let nextAction: UIAlertAction = UIAlertAction(title: "OK", style: .Default) { action -> Void in
        //Do some other stuff
            }
            actionSheetController.addAction(nextAction)
            //Add a text field
            actionSheetController.addTextFieldWithConfigurationHandler { textField -> Void in
        // you can use this text field
        inputTextField = textField
            }

            //Present the AlertController
            self.presentViewController(actionSheetController, animated: true, completion: nil)
Sabareesh
  • 3,585
  • 2
  • 24
  • 42
11

In Swift 3

    let alert = UIAlertController(title: "Alert Ttitle", message: "Alert Message", preferredStyle:
        UIAlertControllerStyle.alert)

    alert.addTextField(configurationHandler: textFieldHandler)

    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in


    }))

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

func textFieldHandler(textField: UITextField!)
    {
        if (textField) != nil {
            textField.text = "Filename"
        }
    }
Kobe Yu
  • 121
  • 1
  • 5
9

Swift 4:

var textField: UITextField?

func configurationTextField(textField: UITextField!) {
    if (textField) != nil {
        self.textField = textField!        //Save reference to the UITextField
        self.textField?.placeholder = "Some text";
    }
}

func openAlertView() {
    let alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.alert)
    alert.addTextField(configurationHandler: configurationTextField)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:nil))
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler:{ (UIAlertAction) in
        print("User click Ok button")
    }))
    self.present(alert, animated: true, completion: nil)
}
Kavin Varnan
  • 1,989
  • 18
  • 23
3

Updated for swift 3 :

used below simple code:

    func showAlertWithTwoTextFields() {

        let alertController = UIAlertController(title: "Add Event", message: "Enter event and it's description", preferredStyle: .alert)

        let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
            alert -> Void in

            let eventNameTextField = alertController.textFields![0] as UITextField
            let descriptionTextField = alertController.textFields![1] as UITextField

            print("firstName \(String(describing: eventNameTextField.text)), secondName \(String(describing: descriptionTextField.text))")

            if eventNameTextField.text != "" || descriptionTextField.text != ""{

            }else{
               // self.showAlertMessageToUser(title: "Alert", messageToUser: "Fields should not be empty, Please enter given info...")
// Show Alert Message to User As per you want
            }

        })

        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
            (action : UIAlertAction!) -> Void in

        })

        alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "Enter event Name"
        }
        alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "Enter event description in short"
        }

        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)

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

// Enjoy Coding...!

Kiran Jadhav
  • 3,209
  • 26
  • 29
1

Swift 2.2

import UIKit

extension UIAlertController {
    // MARK: - UIAlertController+Present

    private struct ButtonsName {
        static let Ok = NSLocalizedString("uIAlertController.buttonName.ok", comment: "")
        static let Cancel = NSLocalizedString("uIAlertController.buttonName.cancel", comment: "")
    }


    class func suggestionAlertViewWithTitle(title:String?, placeholder:String, message:String, presenter:UIViewController, destructive:Bool = false,
                                            okButtonCompletion:((enteredSuggestion:String?)->Void)?, cancelButtonCompletion:(()->Void)?, presentCompletion:(()->Void)?) {
        var alertTitle = UIAlertController.appName()
        if let userTitle = title {
            alertTitle = userTitle
        }

        let controller = UIAlertController(title: alertTitle, message: message, preferredStyle: .Alert)
        let okAction = UIAlertAction(title: ButtonsName.Ok, style: destructive == true ? .Destructive : .Default) { (action) in
            if let okButtonCompletion = okButtonCompletion {
                let text = controller.textFields?.first?.text
                dispatch_async(dispatch_get_main_queue(), {
                    okButtonCompletion(enteredSuggestion: text)
                })
            }
        }
        let cancelAction = UIAlertAction(title: ButtonsName.Cancel, style: .Cancel) { (action) in
            if let cancelButtonCompletion = cancelButtonCompletion {
                dispatch_async(dispatch_get_main_queue(), {
                    cancelButtonCompletion()
                })
            }
        }

        controller.addAction(okAction)
        controller.addAction(cancelAction)
        controller.addTextFieldWithConfigurationHandler { (textField) in
            textField.placeholder = placeholder
        }

        dispatch_async(dispatch_get_main_queue(), {
            presenter.presentViewController(controller, animated: true, completion: presentCompletion)
        })
    }

    // MARK: - Private

    private static func appName () -> String {
        return NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
    }
}

usage:

    UIAlertController.suggestionAlertViewWithTitle(nil, placeholder: placeholder, message: message,
                                                          presenter: self, destructive: false,
                                                          okButtonCompletion: { (enteredSuggestion) in
                self.logger.sendAllLogs(self.currentUser, suggestedTitle: enteredSuggestion)
        }, cancelButtonCompletion:nil, presentCompletion: nil)

a little bit overloaded, but u can always make some parameters optional or/and default

hbk
  • 10,908
  • 11
  • 91
  • 124
0

I see you're already using the new UIAlertController -- good idea, since there's little use in old API if you're usung Swift anyway. But alert.textFieldAtIndex: won't work for that; it's for UIAlertView only.

Luckily, UIAlertController has a method for adding text fields.

rickster
  • 124,678
  • 26
  • 272
  • 326