Rotate UIImageView Depending on iPhone Orientation

后端 未结 1 1181
独厮守ぢ
独厮守ぢ 2021-02-15 11:46

How would I do this, all I want to do is rotate a UIImageView depending on the orientation of the iPhone.

1条回答
  •  死守一世寂寞
    2021-02-15 12:44

    You can do this through IB, to get an app with a portrait and a landscape layout, or you can do it programmatically. This is about the programmatic way.

    To get notifications on the change of orientation, use

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self
                    selector:@selector(orientationChanged)
                    name:UIDeviceOrientationDidChangeNotification
                    object:nil];
    

    and add a function like this (note this is copypasted from a project and a lot of lines are left out, you will need to tune the transformation to your specific situation)

    -(void)orientationChanged
    {
        UIDeviceOrientation o = [UIDevice currentDevice].orientation;
    
        CGFloat angle = 0;
        if ( o == UIDeviceOrientationLandscapeLeft ) angle = M_PI_2;
        else if ( o == UIDeviceOrientationLandscapeRight ) angle = -M_PI_2;
        else if ( o == UIDeviceOrientationPortraitUpsideDown ) angle = M_PI;
    
        [UIView beginAnimations:@"rotate" context:nil];
        [UIView setAnimationDuration:0.7];
        self.rotateView.transform = CGAffineTransformRotate(
                                    CGAffineTransformMakeTranslation(
                                        160.0f-self.rotateView.center.x,
                                        240.0f-self.rotateView.center.y
                                    ),angle);
        [UIView commitAnimations];
    }
    

    When you're done, stop the notifications like so:

    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    

    0 讨论(0)
提交回复
热议问题