iOS屏幕变换的处理(1)

 

iOS屏幕变换,比如从竖屏转为横屏,虽然可以直接使用UIViewController的:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)

 

但是,因为屏幕变换一般都要在视图(UIView)中处理,这种写法对视图并不方便。

也可以覆盖UIView的: - (void)layoutSubviews

 

在该方法中调整自身的frame属性。不过该方法应该是用于对自身的子视图做处理的方法:

    Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.

因此,也不适合。

 

实际上,如果屏幕的方向变化,系统会发出通知,只要注册通知,就可以正确处理屏幕的变换了。

首先,在需要变换的视图init方法注册通知:

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

 

然后,用如下方法处理通知到来的处理:

-(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—> %@",self); 
}

 

这里使用了:

float height=[[UIScreen mainScreen]bounds].size.height*[[UIScreen mainScreen] scale];

 

是因为,如果使用iPhone4,得到的[[UIScreen mainScreen]bounds].size.height值是480,还需要乘以它的缩放系数([[UIScreen mainScreen] scale])才是正确的值。

 

 

原文地址:http://marshal.easymorse.com/archives/4539

 

发布了7 篇原创文章 · 获赞 7 · 访问量 9万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章