将文本保留在警报视图中,并将文本保存到NSString?

时间:2014-04-29 13:16:12

标签: objective-c uitableview uitextfield uialertview

我有一个UITableView,意思是有一个名单。我希望每当点击一个名字时都会显示UIAlertView,这样就可以更改名称的附带信息(现在只是年龄)。

截至目前,我可以显示alertView UITextField,但是一旦关闭alertView,text内的UITextField会重置为占位符。如何让文字与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];
}

另外,如何从UIAlertView获取文字,并将其另存为NSString

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要将视图控制器设置为委托,然后检索回调中的值。您还需要将UIAlertViewDelegate添加到@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

}