Question

I'm the beginner for Objective-C as well as English is not my native language so if my sentences are mess, I'm sorry.

I have two view controller and both are tableViewController:
- view controller A is my main view controller.
- view controller B is able to pick the color of NavigationBar's barTintColor, so if I select row 0, it makes barTintColor to red both A and B.

I put 5 different types of color so that means I have 5 rows to pick a color from. If I choose red color for this time and made the app terminate, then start app again, how can I show the red color even if I not choosing red color again?

I know that I can save the settings by using NSUserDefaults.
So, in my view controller B, I did:

-(void)tableView:(UITableView *)tableView
       didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[NSUserDefaults standardUserDefaults]setInteger:indexPath.row forKey:@"ChosenColor"];

}

However, where I want to save the setting and where I want load the setting is different view controller so I don't know how I can load this.

How can I solve this problem??

Was it helpful?

Solution

I will suppose that you hace an NSArray to know which color is every row in the TableView.

Then you can save the color in NSUserDefaults instead of an Integer.

-(void)tableView:(UITableView *)tableView
   didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        [[NSUserDefaults standardUserDefaults] setObject:[UIColor redColor] forKey:@"ChosenColor"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

Then, when you reopen the app you can retrieve this data in viewDidAppear: with:

- (void) viewDidAppear:(BOOL)animated
{
    UIColor *color = [[NSUserDefaults standardUserDefaults] objectForKey:@"ChosenColor"];
    [yourObject setColor:color];
}

However, because you are trying to do something for the whole app. You can do it in your AppDelegate.m.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Usually your UINavigationController will be your rootViewController
    UIColor *color = [[NSUserDefaults standardUserDefaults] objectForKey:@"ChosenColor"];
    UINavigationController * navigationController =(UINavigationController *)self.window.rootViewController;
    [navigationController.navigationBar setBarTintColor:color];
}

If you want to pick a color in one ViewController and go back to your main ViewController and set the selected color you should use a Delegate, too. If you don't know about delegation, check this links:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top