在我的 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/