Marcelo
Marcelo

Reputation: 1196

Prevent interface from changing during rotation

I want to support all orientations but portrait. I wanted to do some simple but I never was not able to find a solution.

I have 6 big buttons in my interface. Plus 2 extra small buttons.

When the orientation changes, I want to keep ALL 8 buttons in the same center/place, I just wanted to rotate the 6 big buttons, so they will be facing the right way.

I tried setting

- (BOOL)shouldAutorotate
{
    return NO;
}

and sending myself a notification but I would have to deal with the old orientation vs the new orientation in order to rotate to the right position. Is there any other possibility? Plus I was never able to get the previous orientation as the notification was sent after the orientation changed (UIDeviceOrientationDidChangeNotification)

Upvotes: 0

Views: 92

Answers (1)

Eyal
Eyal

Reputation: 10818

This is what I use to rotate a button's image when the view rotate:

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceOrientationDidChangeNot:) name:UIDeviceOrientationDidChangeNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}  

- (void)handleDeviceOrientationDidChangeNot:(NSNotification *)not {
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    CGFloat angle = 0.0;
    switch (orientation) {
        case UIDeviceOrientationPortrait:
            angle = 0.0;
            break;
        case UIDeviceOrientationLandscapeLeft:
            angle = M_PI/2;
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            angle = M_PI;
            break;
        case UIDeviceOrientationLandscapeRight:
            angle = -M_PI/2;
            break;
        default:
            return;
            break;
    }

    [UIView animateWithDuration:0.35 animations:^{
        self.someButton.imageView.transform = CGAffineTransformMakeRotation(angle);
    } completion:^(BOOL finished) {
        //
    }];
}

Upvotes: 1

Related Questions