ios屏幕旋转的处理

在iOS中的屏幕变换,也就是横竖屏的转换,虽然可以直接使用UIViewController的

– willRotateToInterfaceOrientation:duration:

– willAnimateRotationToInterfaceOrientation:duration:

– didRotateFromInterfaceOrientation:

– willAnimateFirstHalfOfRotationToInterfaceOrientation:duration:

– didAnimateFirstHalfOfRotationToInterfaceOrientation:

– willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:

这些函数来响应屏幕旋转时候的事件。之所以相应这些事件当然是为了对视图的显示进行处理,这种写法对于视图的处理并不是十分方便。

还有一种方法就是覆盖UIVIew的

-(void)layoutSubviews方法,在该方法中调整自身的frame的属性,但是苹果文档中也说明了,这个方法是用语对自身的子视图做处理的方法。

 

上面的两种方法虽然都可以实现在屏幕旋转时候对视图进行处理,但是并不理想。

实际上,我们可以使用通知来实现。当屏幕的方向变化的时候,只要注册通知,就可以正确处理屏幕的变换了。

首先我们要注册通知,

在哪里注册呢?肯定是在需要变换的视图的initWithFrame方法中注册通知了。

例如:- (id)initWithFrame:(CGRect)frame { 

    self = [super initWithFrame:frame]; 

    if (self) { 

        [[NSNotificationCenter defaultCenter] addObserver:self 

                                                 selector:@selector(changeFrames:) 

                                                     name:UIDeviceOrientationDidChangeNotification 

                                                   object:nil]; 

        self.backgroundColor=[UIColor greenColor]; 

    } 

    return self; 

}

 

之后在写@selector中的函数changeFrames

如下:

-(void)changeFrames:(NSNotification *)notification

{
    NSLog(@"change notification: %@", notification.userInfo);
    float width=[[UIScreen mainScreen]bounds].size.width*[[UIScreen mainScreen] scale];
    float height=[[UIScreen mainScreen]bounds].size.height*[[UIScreen mainScreen] scale];
    if ([[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortrait
        || [[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortraitUpsideDown) 

    {
        NSLog(@"portrait");
        self.frame=CGRectMake(0, 0, height, width);
    }

     else

     {
        NSLog(@"landscape");
        self.frame=CGRectMake(0, 0, width, height);
     }

    NSLog(@"view is %@",self);
}

 

上面使用了scale这个函数,是为了使视图的缩放比例是正确的。

你可能感兴趣的:(ios)