簡體   English   中英

使用UITextField的UIAlertView - 使用NSUserDefaults保存

[英]UIAlertView with UITextField - Saving with 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.我想我錯過了這里顯而易見的。

檢查你的預測。 檢查是否沒有“1”並將其設置為“1”。 也許你應該檢查是否存在對nil用戶默認如沒有名字。

你永遠不會設置Name值,它應該在alertView:clickedButtonAtIndex:完成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];
}

你可以調整它,因為你的邏輯適合你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM