Comment ajouter un champ Text à UIAlertView dans Swift

j'ai ce code, mais je ne sais pas comment afficher un champ de texte dans la vue 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)

j'ai ce code pour textfield , Comment puis-je le montrer dans UIAlerView

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

j'ai aussi essayé ce code:

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

quand je spécifie le plainText AlertStyle, il affiche un champ Text avec un placeholder par défaut,"Login".. Je veux changer cela, je veux montrer un clavier de bloc décimal. Je veux aussi gérer la valeur dans laquelle l'utilisateur entre le textField. Quelqu'un peut-il m'aider?

31
demandé sur Stonz2 2014-06-07 08:19:36

9 réponses

Vous pouvez accéder au champ de texte avec:

let textField = alert.textFieldAtIndex(0)

puis modifier le texte du paramètre:

textField.placeholder = "Foo!"

Et le type de clavier:

textField.keyboardType = ...
32
répondu David Berry 2016-10-14 04:54:09

essayez ce Code (avec 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")
        })

Pouvez-vous voir aussi ma réponse ici

19
répondu Guy Kahlon 2017-05-23 12:18:06

Objectif 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];

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

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"
}
14
répondu Darshit Shah 2017-01-17 14:32:30
            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)
13
répondu Sabareesh 2015-03-26 09:34:55

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"
        }
    }
8
répondu Kobe Yu 2016-10-19 12:31:29

utilisé en dessous du code simple:

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

// De Profiter De Codage...!

2
répondu Kiran jadhav 2017-08-26 10:49:51

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)
}
2
répondu Kavin Varnan 2018-03-31 07:19:40

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

utilisation:

    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)

un peu surchargé, mais u peut toujours rendre certains paramètres optionnels ou / et par défaut

1
répondu gbk 2016-11-10 16:06:35

je vois que vous utilisez déjà le nouveau UIAlertController -- bonne idée, puisqu'il y a peu d'utilité dans L'ancienne API si vous utilisez Swift de toute façon. Mais alert.textFieldAtIndex: ne fonctionne pas pour ça; c'est pour UIAlertView une seule.

Heureusement, UIAlertController a une méthode pour ajouter des champs de texte.

0
répondu rickster 2014-06-07 05:50:15