確認視窗 Alert 使用方法
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意!" message:@"您確定要將這筆資料從我的最愛中移除嗎?" preferredStyle:UIAlertControllerStyleAlert];2.
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"移除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { self.navigationItem.rightBarButtonItem = off; [favorite removeObject:self.item]; [[NSUserDefaults standardUserDefaults] setObject:favorite forKey:@"FAVORITE"]; [[NSUserDefaults standardUserDefaults] synchronize]; }]; UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];3.
[alert addAction:ok]; [alert addAction:cancel];4.
[self presentViewController:alert animated:YES completion:nil];
5.寫入NSUserDefault
因為UIAlertAction 最後的handler是異步方法
在使用者點選後才會執行,必須把寫入方法寫在執行後才寫入。不然畫面不會刷新
CODE:
if (sender == off) { ///加入我的最愛 self.navigationItem.rightBarButtonItem = on; [favorite addObject:self.item]; [[NSUserDefaults standardUserDefaults] setObject:favorite forKey:@"FAVORITE"]; [[NSUserDefaults standardUserDefaults] synchronize]; } else { ///從我的最愛移除 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意!" message:@"您確定要將這筆資料從我的最愛中移除嗎?" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *ok = [UIAlertAction actionWithTitle:@"移除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { self.navigationItem.rightBarButtonItem = off; [favorite removeObject:self.item]; [[NSUserDefaults standardUserDefaults] setObject:favorite forKey:@"FAVORITE"]; [[NSUserDefaults standardUserDefaults] synchronize]; }]; UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; [alert addAction:ok]; [alert addAction:cancel]; [self presentViewController:alert animated:YES completion:nil]; }
留言
張貼留言