iOS屏幕變換的處理(2)

上一節提到了通過通知來處理屏幕視圖的自動翻轉。

藍色的子視圖,在翻轉的情況下觸發界面大小的調整。

還是使用通知機制,即:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(doRotateAction:)
                                             name:@"UIDeviceOrientationDidChangeNotification"
                                           object:nil];

 

不過,這裏發現了個問題,當執行通知觸發方法的時候,發現總是執行了多次。其中多出來的情況,設備的方向是不對的:

[UIDevice currentDevice].orientation==UIDeviceOrientationUnknown

 

如上面代碼,返回的值是UIDeviceOrientationUnknown,也就是0。只許過濾這種情況即可,下面是比較完整的視圖實現代碼:

@implementation ContentView

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(doRotateAction:)
                                                     name:@”UIDeviceOrientationDidChangeNotification”
                                                   object:nil];
    }
    return self;
}

-(void) doRotateAction:(NSNotification *) notification{
    if([UIDevice currentDevice].orientation!=UIDeviceOrientationUnknown){
        NSLog(@”do rotate action: %d”,[[notification object] orientation]);
        if([UIDevice currentDevice].orientation==UIDeviceOrientationPortrait||
           [UIDevice currentDevice].orientation==UIDeviceOrientationPortraitUpsideDown){
            self.frame=CGRectMake(self.frame.origin.x, self.frame.origin.y, 200, 200);
        }else{
            self.frame=CGRectMake(self.frame.origin.x, self.frame.origin.y, 600, 500);
        }
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


 

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

 

發佈了7 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章