Voglio ottenere il nome utente. Una semplice finestra di dialogo per l'immissione di testo. Qualche modo semplice per farlo?
Voglio ottenere il nome utente. Una semplice finestra di dialogo per l'immissione di testo. Qualche modo semplice per farlo?
Risposte:
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):

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:

È 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!
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):

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

NOTA: di seguito non funziona con iOS 7 (iOS 4 - 6 Works)
Solo per aggiungere un'altra versione.

- (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) {
...
}
}
alertView:(UIAlertView *) clickedButtonAtIndex:(NSInteger)buttonIndexmetodo delegato per recuperare il valore di textField.text: `NSString * theMessage = [alertView textFieldAtIndex: 0] .text;`
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];
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];
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.
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;
}
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)
Vorrei usare a UIAlertViewcon una UITextFieldsottoview. Puoi aggiungere manualmente il campo di testo o, in iOS 5, utilizzare uno dei nuovi metodi.
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];
Aggiungi visualizzazioni a UIAlertView in questo modo . In iOS 5 ci sono alcune cose "magiche" che lo fanno per te (ma è tutto sotto NDA).
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();
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
})
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];