ios - 带有 UITextField 的 UIAlertView - 使用 NSUserDefaults 保存

标签 ios tableview alertview

在我的 ViewDidLoad 的 .m 文件中,我有以下代码:

 if (![@"1" isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"Name"]]) {
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"Name"];
    [[NSUserDefaults standardUserDefaults] synchronize];


UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"What is your name?" message:@"\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Send", nil];

UITextField *utextfield = [[UITextField alloc] initWithFrame:CGRectMake (9.0, 60.0, 260.0, 25.0)]; utextfield.placeholder =@"Username";
[utextfield setBackgroundColor:[UIColor whiteColor]];
[alertview addSubview:utextfield];

[alertview show];

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

}

如您所见,用户可以在此处保存他的名字,这样他就不必一遍又一遍地输入。除此之外,如果他进入了它,他将不会再被问到。但是应用程序在加载时没有显示名称,而是显示数字 1。我想我在这里遗漏了显而易见的东西。

最佳答案

您永远不会设置名称值,它应该在 alertView:clickedButtonAtIndex: 中完成

我还建议取消 @"1",并检查 nil(如 @Roman 所建议的)或将 BOOL 存储在另一个默认键中。

...
utextfield.tag = 9876; // some value likely not in use by the internals



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  if (buttonIndex == alertView.cancelButtonIndex) {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Name"];
  } else if (buttonIndex == alertView.firstOtherButtonIndex) {
    UITextField *utextfield = (UITextField *)[alertView viewWithTag:9876];
    [[NSUserDefaults standardUserDefaults] setValue:utextfield.text forKey:@"Name"];
  }
  [[NSUserDefaults standardUserDefaults] synchronize];
}

你可以根据自己的逻辑进行调整

关于ios - 带有 UITextField 的 UIAlertView - 使用 NSUserDefaults 保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8761732/

相关文章:

android - 使用 xamarin 构建可在 native 应用程序中使用的跨平台库

ios - 如何在滚动时突出显示/更改表格 View 部分标题的背景颜色

ios - 如何从 alertview 获取 textview 的值

ios - 警报错误并动态显示隐藏的 UILabel

ios - 使用 Coredata 学习 Swift : why don't I get any UITableViewCells?

iOS 获取特定的 UITableViewCell

ios - CoreData 扩展 - 将模型添加到目标时为 'Use of Undeclared Identifier'

swift - 在 Swift 中,如何使动态 tableView 单元格可选择,以便当按下它时它会传输到不同的 tableViewController?

ios - Swift/UITableView 将随机行插入到部分以发布 AdMob 广告

当键盘打开时 View 更改后出现带有白色文本的 ios 黑色键盘