UIAlertView 与 UITextField - 使用 NSUserDefaults 保存
在我的 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。我想我在这里遗漏了明显的内容。
In the .m file of my ViewDidLoad I have the following code:
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{
}
As you can see the user can save his name here so he doesn't have to enter it over and over again. In addition to that he won't get asked again if he entered it. BUT instead of displaying the name when its loaded, the app displays the number 1. I guess I'm missing the obvious here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您永远不会设置 Name 值,应该在
alertView:clickedButtonAtIndex:
中完成我还建议取消 @"1",并检查 nil (如 @Roman 建议)或存储另一个默认键中的 BOOL。
你可以根据你的逻辑进行调整
You are never setting the Name value, it should be done in
alertView:clickedButtonAtIndex:
I would also suggest doing away with the @"1", and either checking for nil (as @Roman suggests) or storing a BOOL in another defaults key.
you can adjust that as your logic suits you
检查你的 if 预测。您检查是否没有“1”,然后将其设置为“1”。也许你应该检查是否有
nil
,例如用户默认值中没有名称。Check your if prediction. You check if there's not "1" and than set it to "1". maybe you should check if there's
nil
e.g. no name in user defaults.