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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章