Qual è un modo semplice per ottenere una finestra di dialogo popup di immissione testo su un iPhone


125

Voglio ottenere il nome utente. Una semplice finestra di dialogo per l'immissione di testo. Qualche modo semplice per farlo?


1
aspetta solo qualche mese, fino a circa settembre, e la tua vita sarà molto più semplice.
Jonathan.

Risposte:


264

In iOS 5 c'è un modo nuovo e semplice per farlo. Non sono sicuro che l'implementazione sia ancora completamente completa in quanto non è una grazia come, diciamo, a UITableViewCell, ma dovrebbe sicuramente fare il trucco in quanto è ora standard supportato nell'API iOS. Non avrai bisogno di un'API privata per questo.

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"This is an example alert!" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
[alert release];

Questo rende un avviso Visualizza in questo modo (screenshot tratto dal simulatore di iPhone 5.0 in XCode 4.2):

esempio di avviso con alertViewStyle impostato su UIAlertViewStylePlainTextInput

Quando si preme un pulsante qualsiasi, verranno chiamati i normali metodi delegati ed è possibile estrarre il textInput lì in questo modo:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    NSLog(@"Entered: %@",[[alertView textFieldAtIndex:0] text]);
}

Qui ho appena registrato NSLog i risultati che sono stati inseriti. Nel codice di produzione, dovresti probabilmente tenere un puntatore a alertView come variabile globale o utilizzare il tag alertView per verificare se la funzione delegata è stata chiamata dall'appropriato, UIAlertViewma per questo esempio dovrebbe andare bene.

Dovresti dare un'occhiata all'API UIAlertView e vedrai che ci sono altri stili definiti.

Spero che questo abbia aiutato!

-- MODIFICARE --

Stavo giocando con l'avviso Visualizza un po 'e suppongo che non abbia bisogno di alcun annuncio che è perfettamente possibile modificare il campo di testo come desiderato: è possibile creare un riferimento a UITextFielde modificarlo normalmente (programmaticamente). In questo modo ho creato un alertView come specificato nella domanda originale. Meglio tardi che mai, giusto :-)?

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Please enter your name:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeNumberPad;
alertTextField.placeholder = @"Enter your name";
[alert show];
[alert release];

Questo produce questo avviso:

UIAlertView che utilizza UIAlertViewPlainTextInput alertStyle per chiedere un nome utente

È possibile utilizzare lo stesso metodo delegato del poster precedente per elaborare il risultato dall'input. Non sono sicuro se è possibile impedire il UIAlertViewlicenziamento (non esiste una shouldDismissfunzione delegata AFAIK), quindi suppongo che se l'input dell'utente non è valido, è necessario inserire un nuovo avviso (o semplicemente re showquesto) fino a quando l'input corretto è stato entrato.

Divertiti!


1
Con il conteggio di riferimento automatico, non dovresti più conservare e rilasciare oggetti da solo.
Waqleh,

5
Lo so, ma questa risposta è stata scritta nel 2011.
Warkst,

3
Il metodo è ammortizzato da IOS 9.0. Usa invece UIAlertController:
EckhardN

Se siete alla ricerca di sostegno con Swift 4: stackoverflow.com/a/10689318/525576
John Riselvato

186

Per essere sicuri di ricevere le chiamate dopo che l'utente ha inserito il testo, impostare il delegato all'interno del gestore di configurazione. textField.delegate = self

Swift 3 e 4 (iOS 10-11):

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
    textField.placeholder = "Enter text:"
    textField.isSecureTextEntry = true // for password input
})
self.present(alert, animated: true, completion: nil)

In Swift (iOS 8-10):

inserisci qui la descrizione dell'immagine

override func viewDidAppear(animated: Bool) {
    var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Enter text:"
        textField.secureTextEntry = true
        })
    self.presentViewController(alert, animated: true, completion: nil)
}

In Objective-C (iOS 8):

- (void) viewDidLoad 
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Click" style:UIAlertActionStyleDefault handler:nil]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Enter text:";
        textField.secureTextEntry = YES;
    }];
    [self presentViewController:alert animated:YES completion:nil];
}

PER iOS 5-7:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"INPUT BELOW" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];

inserisci qui la descrizione dell'immagine


NOTA: di seguito non funziona con iOS 7 (iOS 4 - 6 Works)

Solo per aggiungere un'altra versione.

UIAlert con UITextField

- (void)viewDidLoad{

    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Preset Saving..." message:@"Describe the Preset\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
    UITextField *textField = [[UITextField alloc] init];
    [textField setBackgroundColor:[UIColor whiteColor]];
    textField.delegate = self;
    textField.borderStyle = UITextBorderStyleLine;
    textField.frame = CGRectMake(15, 75, 255, 30);
    textField.placeholder = @"Preset Name";
    textField.keyboardAppearance = UIKeyboardAppearanceAlert;
    [textField becomeFirstResponder];
    [alert addSubview:textField];

}

poi chiamo [alert show];quando lo voglio.

Il metodo che segue

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {         
    NSString* detailString = textField.text;
    NSLog(@"String is: %@", detailString); //Put it on the debugger
    if ([textField.text length] <= 0 || buttonIndex == 0){ 
        return; //If cancel or 0 length string the string doesn't matter
    }
    if (buttonIndex == 1) {
        ...

    }
}


1
Ho avuto qualcosa di simile da IOS 4 ma sembra non funzionare in OS 7 Ora usa il codice di Wakrst - salva molte righe di codice.
Dave Appleton,

Quindi, quale sarebbe il modo corretto di farlo per iOS7? Stiamo costruendo con iOS6 SDK ma mostra ancora strano su iOS7.
sebrock,

Aggiunto il supporto per iOS7 alla domanda
John Riselvato,

1
Ho scoperto che dovevo inserire quanto segue nel mio alertView:(UIAlertView *) clickedButtonAtIndex:(NSInteger)buttonIndexmetodo delegato per recuperare il valore di textField.text: `NSString * theMessage = [alertView textFieldAtIndex: 0] .text;`
James Perih,

1
sostituisci "var alert" con "let alert" nel codice rapido per conformarti all'ultima versione di swift
Matei Suica,

11

Testato il terzo frammento di codice di Warkst - ha funzionato alla grande, tranne per il fatto che l'ho modificato in modo che fosse un tipo di input predefinito anziché numerico:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Please enter your name:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeDefault;
alertTextField.placeholder = @"Enter your name";
[alert show];

Buon punto! All'epoca stavo scherzando con textField e ho dimenticato di cambiare il tipo di tastiera prima di caricare lo snippet di codice. Sono contento che il mio codice possa aiutarti!
Warkst,

11

Da IOS 9.0 utilizzare UIAlertController:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
                                                           message:@"This is an alert."
                                                          preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction * action) {
                    //use alert.textFields[0].text
                                                       }];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {
                                                          //cancel action
                                                      }];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    // A block for configuring the text field prior to displaying the alert
}];
[alert addAction:defaultAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];

5

Volevo solo aggiungere un'importante informazione che credo fosse stata esclusa forse con il presupposto che quelli in cerca di risposte potessero già sapere. Questo problema si verifica molto e anche io mi sono trovato bloccato quando ho provato a implementare il viewAlertmetodo per i pulsanti del UIAlertViewmessaggio. Per fare ciò è necessario prima aggiungere la classe delegata che potrebbe assomigliare a questa:

@interface YourViewController : UIViewController <UIAlertViewDelegate>

Inoltre puoi trovare un tutorial molto utile qui !

Spero che questo ti aiuti.


5

Prova questo codice Swift in un UIViewController -

func doAlertControllerDemo() {

    var inputTextField: UITextField?;

    let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert);

    passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)

        let entryStr : String = (inputTextField?.text)! ;

        print("BOOM! I received '\(entryStr)'");

        self.doAlertViewDemo(); //do again!
    }));


    passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        print("done");
    }));


    passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Password"
        textField.secureTextEntry = false       /* true here for pswd entry */
        inputTextField = textField
    });


    self.presentViewController(passwordPrompt, animated: true, completion: nil);


    return;
}

3

Swift 3:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
     textField.placeholder = "Enter text:"
})

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

2

Vorrei usare a UIAlertViewcon una UITextFieldsottoview. Puoi aggiungere manualmente il campo di testo o, in iOS 5, utilizzare uno dei nuovi metodi.


Ho aggiunto il seguente codice da un altro post, ma il popup appare fuori dallo schermo (molto in alto, con solo la metà inferiore visibile)
user605957

2
codeUIAlertView * myAlertView = [[[UIAlertView alloc] initWithTitle: @ Messaggio "Titolo qui": @ "questo viene coperto" delegato: self cancelButtonTitle: @ "Annulla" otherButtonTitles: @ "OK", nil]; UITextField * myTextField = [[[UITextField alloc] initWithFrame: CGRectMake (12.0, 45.0, 260.0, 25.0)]; CGAffineTransform myTransform = CGAffineTransformMakeTranslation (0.0, 130.0); [myAlertView setTransform: myTransform]; [myTextField setBackgroundColor: [UIColor whiteColor]]; [myAlertView addSubview: myTextField]; [myAlertView show]; [versione di myAlertView];
user605957,

Ho provato un codice simile e visualizza la vista di avviso con casella di testo e pulsanti ma non c'è abbastanza spazio per il campo di testo, è bloccato tra il titolo e i pulsanti e li tocca entrambi. Ho provato alcune trasformazioni per ridimensionare la cornice ma i pulsanti rimangono dove erano, quindi devono essere spostati anche. Non so come riposizionare i pulsanti e non posso credere che tutto ciò sia necessario per recuperare una singola riga di testo da un prompt all'utente. Non c'è un modo migliore di questo?
Dean Davids,

2

Aggiungi visualizzazioni a UIAlertView in questo modo . In iOS 5 ci sono alcune cose "magiche" che lo fanno per te (ma è tutto sotto NDA).


Ho provato questo e funziona in qualche modo. Tranne il popup è fuori dallo schermo (la metà superiore del popup è troncata). Qualche idea sul perché?
user605957,

Ho avuto lo stesso problema, rimuovendo il setTranformMakeTranslation (0,109) l'ho risolto su iPad e iPhone. Si presentò nel posto giusto senza di essa.
riunito il

2

In Xamarin e C #:

var alert = new UIAlertView ("Your title", "Your description", null, "Cancel", new [] {"OK"});
alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
alert.Clicked += (s, b) => {
    var title = alert.ButtonTitle(b.ButtonIndex);
    if (title == "OK") {
        var text = alert.GetTextField(0).Text;
        ...
    }
};

alert.Show();

0

Basandosi sulla risposta di John Riselvato, per recuperare la stringa da UIAlertView ...

alert.addAction(UIAlertAction(title: "Submit", style: UIAlertAction.Style.default) { (action : UIAlertAction) in
            guard let message = alert.textFields?.first?.text else {
                return
            }
            // Text Field Response Handling Here
        })

-1
UIAlertview *alt = [[UIAlertView alloc]initWithTitle:@"\n\n\n" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(25,17, 100, 30)];
lbl1.text=@"User Name";

UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(25, 60, 80, 30)];
lbl2.text = @"Password";

UITextField *username=[[UITextField alloc]initWithFrame:CGRectMake(130, 17, 130, 30)];
UITextField *password=[[UITextField alloc]initWithFrame:CGRectMake(130, 60, 130, 30)];

lbl1.textColor = [UIColor whiteColor];
lbl2.textColor = [UIColor whiteColor];

[lbl1 setBackgroundColor:[UIColor clearColor]];
[lbl2 setBackgroundColor:[UIColor clearColor]];

username.borderStyle = UITextBorderStyleRoundedRect;
password.borderStyle = UITextBorderStyleRoundedRect;

[alt addSubview:lbl1];
[alt addSubview:lbl2];
[alt addSubview:username];
[alt addSubview:password];

[alt show];
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.