Question

So I have a good animation showing on a tab bar, but I want to be able to allow the user to turn off the animation if they want.

//MainViewController.m

- (void) animateTabBar{
    [UIView animateWithDuration:(TAB_BAR_ANIMATION_TIME / 2) animations:^{
        CGPoint rightOffset = CGPointMake(self.tabBarScrollView.contentSize.width -    self.tabBarScrollView.bounds.size.width, 0);
        [self.tabBarScrollView setContentOffset:rightOffset];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:(TAB_BAR_ANIMATION_TIME / 2) animations:^{
            [self.tabBarScrollView setContentOffset:CGPointMake(0, 0)];
        }];
    }];
}

I use this within my other code to actually make it move

[self animateTabBar];

How can I have this to be toggle with a UISwitch on my Settings so the user can turn this off.

Here's an abstract of how it should work, but obviously it's not working correctly.

// SettingsViewController.m

-(IBAction)onOffSwitch:(id)sender{

if(onOffSwitch.on) {
    // Animation is on
    [self animateTabBar];
}

else {
    // No animation
}

}
Was it helpful?

Solution

Seems like since this is a user preference, the correct place to save it would be in the NSUserDefaults, so you can try this in your settings:

The switch should be a "Not show animation", so when it is On, is not showing the animation, and initially would be Off(which shows the animation)

-(IBAction)onOffSwitch:(UISwitch *)sender{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:sender.on forKey:@"ShouldNotShowAnimation"];
    [defaults synchronize];
}

And in your animation, you can add

- (void) animateTabBar{
    if ([NSUserDefaults standardUserDefaults] boolForKey:@"ShouldNotShowAnimation"]) return;
    [UIView animateWithDuration:(TAB_BAR_ANIMATION_TIME / 2) animations:^{
        CGPoint rightOffset = CGPointMake(self.tabBarScrollView.contentSize.width -        self.tabBarScrollView.bounds.size.width, 0);
        [self.tabBarScrollView setContentOffset:rightOffset];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:(TAB_BAR_ANIMATION_TIME / 2) animations:^{
            [self.tabBarScrollView setContentOffset:CGPointMake(0, 0)];
        }];
    }];
}

I added just one line, that checks in the user defaults and then quits (no animation) if "ShouldNotShowAnimation" is YES.

If it is no, then it will show the animation. And since the boolForKey: returns NO if it cannot find the user default, it will show the animation if it has not been set before.

EDIT

To show the UISwitch correctly in the settings view, add this in the viewWillAppear method

self.switch.on = [NSUserDefaults standardUserDefaults] boolForKey:@"ShouldNotShowAnimation"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top