A common mistake that people make when using a UIAlertView
is that they think that sending it a show
message will block the main thread. It does not. Your code continues to execute, even though there is an alert on the screen. Thus, no value exists for the UITextField
that you have passed in.
What you need to do is implement the UIAlertViewDelegate
in your UIViewController
to grab whatever a user has entered into the text field. That said, you still have to check for a nil
value, because if you don't type anything in, the text
value will be nil
.
UPDATE: This answer was posted before Apple created an API for adding a UITextField
to an alert through the UIAlertViewStyle
. Here is the updated code, borrowed from @matt
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter Name"
message:@" "
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
Then, in the UIAlertViewDelegate
call back:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *name = [alertView textFieldAtIndex:0].text;
// Insert whatever needs to be done with "name"
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…