根据iPhone方向旋转UIImageView

8

我该如何做到这一点,我只想根据iPhone的方向旋转UIImageView

1个回答

18

您可以通过IB来获取一个具有纵向和横向布局的应用程序,也可以通过编程方式实现。以下是关于编程方式的内容。

如果想要获取方向改变的通知,请使用:

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

然后添加一个类似于这样的函数(注意,这是从一个项目中复制粘贴的,有很多行被省略了,你需要根据你具体的情况来调整转换)

-(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];
}

当你完成时,可以像这样停止通知:

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

嗯,这对我来说似乎并不完美,因为它不会旋转仅在另一个UIView内部的UIImageView / UIView。相反,它旋转整个UIView而不仅仅是子视图。 - Joshua
然后将 self.rotateView 设为你想要旋转的子视图即可。 - mvds
3
你应该使用M_PI_2而不是M_PI/2.0f - Vincent Guerci

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接