首先我的最愛必須存在手機內讓下次打開後可以繼續存用
- 在AppDelegate 裡面寫一個 NSUserDefaults 裡面來判斷是否為第一次登入
- 在AppDelegate -> - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 裡面設定
- 在方法裡面建立一個NSUserDefaults 用來儲存我的最愛項目
- 每次進入頁面時候必須判斷目前點選的資料是否已經存在我的最愛要設定icon狀態on/off
- 當點我的最愛icon時把這個item儲存到 NSUserDefaults 裡面
- 移除我的最愛icon時把這個item從 NSUserDefaults 移除
- 如果有在不同頁面用到同一筆我的最愛中的資料時,其中一個頁面中移除,另一個頁面的我的最愛icon並不會改變。所以有使用到我的最愛功能的頁面進入時檢查一次這筆資料是否有被記錄/移除
if(![[NSUserDefaults standarUserDefaults] objectForKey:@"FAVORITE"]){ [[NSUserDefaults standerUserDefaults] setObject:@[] forKey:@"FAVORITE"]; [[NSUserDefaults standerUserDefaults] synchronize]; }
self.navigationItem.rightBarButtonItem =([favorite indexOfObject:self.item] == NSNotFound)?off:on;
//畫面要出現時檢查 -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear]; //從記錄中讀取 favorite = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"FAVORITE"]]; //重新檢查並設定icon self.navigationItem.rightBarButtonItem = ([favorite indexOfObject:self.item]==NSNotFound)?off:on; }
UIBarButtonItem *on; UIBarButtonItem *off; //讀取NSUserDefaults 資料 NSMutableArray *favorite; favorite = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"FAVORITE"]]; //icon狀態 + 觸發方法 on = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"h_on"] style:UIBarButtonItemStylePlain target:self action:@selector(doSomething:)]; off = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"h_off"] style:UIBarButtonItemStylePlain target:self action:@selector(doSomething:)]; //確認icon 狀態 self.navigationItem.rightBarButtonItem = ([favorite indexOfObject:self.item]==NSNotFound)?off:on; -(void)doSomething:(UIBarButtonItem*)sender{ if (sender == off) { ///加入我的最愛 self.navigationItem.rightBarButtonItem = on; [favorite addObject:self.item]; } else { ///從我的最愛移除 self.navigationItem.rightBarButtonItem = off; [favorite removeObject:self.item]; } [[NSUserDefaults standardUserDefaults] setObject:favorite forKey:@"FAVORITE"]; [[NSUserDefaults standardUserDefaults] synchronize]; NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"FAVORITE"]); }
留言
張貼留言