Pregunta

I have a UITableView that is meant have a list of names. I want it to bring up an UIAlertView whenever a name is clicked, so that the accompanying information to the name (for now just the age) will be allowed to be changed.

As of now, I can get an alertView with a UITextField to appear, however once you close the alertView, the text inside the UITextField resets to the placeholder. How can I get the text to stay with the UIAlertView?

- (void)tableView:(UITableView *)tableView 
        didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIAlertView *alert = 
    [[UIAlertView alloc] initWithTitle:@"Set Age" 
                               message:[_tableData1 objectAtIndex:indexPath.row] 
                              delegate:nil 
                     cancelButtonTitle:@"OK" 
                     otherButtonTitles:nil];

    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *textField = [alert textFieldAtIndex:0];
    textField.placeholder = @"18";
    [alert show];
}

Also, how can I get the text from the UIAlertView, and save it as a NSString?

Thank you!

¿Fue útil?

Solución

You need to set your view controller as the delegate and then retrieve the value in the callback. You also need to add UIAlertViewDelegate to your @interface

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Set Age" message:[_tableData1 objectAtIndex:indexPath.row] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *textField = [alert textFieldAtIndex:0];
    textField.placeholder = @"18";
    [alert show];
}


-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if(buttonIndex == alertView.cancelButtonIndex) {
        return;
    }

    NSString * yourString = [alertView textFieldAtIndex:0].text

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top