iPhone/iPadプログラミングメモ。
縦横どちらの画面でも中心に表示される UIViewを作っていたのですが、
[[UIDevice currentDevice] orientation]
を使っていたら実機で上手くいかなかったのでメモしておきます。
まず、上手くいかなかった理由としては UIDeviceの orientationプロパティには
回転方向だけでなく、画面が上向きか下向きかも存在していたからです。
それぞれ UIDeviceOrientationFaceUp、UIDeviceOrientationFaceDownです。
orientationプロパティでは「縦画面か横画面か」ではなく、本体の向き
であることを覚えておく必要があります。
対応策として、orientationプロパティを保存しておくことにしました。
まずは本体の回転を検知させます。
// 回転の検知を受け取るように設定 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; UIDevice *device = [UIDevice currentDevice]; [center addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:device ]; [device beginGeneratingDeviceOrientationNotifications]; // 現在の方向を保存 deviceOrientation = [device orientation]; center = nil; device = nil;
回転を検知した時に実行されるメソッドです。
-(void)orientationChanged:(NSNotification *)notification{ // 現在の本体の方向 UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; // 画面が天地方向以外なら更新 if ( orientation != UIDeviceOrientationFaceUp && orientation != UIDeviceOrientationFaceDown ) { deviceOrientation = orientation; // 回転時に実行させたいメソッドはここに記述 hogeView.center = [self getScreenCenter]; } }
そして画面の中心を取得するメソッドです。
/******************************** * 画面センターを返す */ -(CGPoint)getScreenCenter{ CGRect rect = [self getScreenRect]; return CGPointMake( rect.size.width/2, rect.size.height/2 ); } /******************************** * 現在の方向による画面サイズ */ -(CGRect)getScreenRect{ // 画面サイズ。縦向きでも横向きでも数値は変わらない。 int screenW = [[UIScreen mainScreen] applicationFrame].size.width; int screenH = [[UIScreen mainScreen] applicationFrame].size.height; CGRect rect; // 方向で縦横サイズを決める switch (deviceOrientation) { // 横 case UIDeviceOrientationLandscapeLeft: case UIDeviceOrientationLandscapeRight: rect = CGRectMake(0, 0, screenH, screenW); break; // 縦 case UIDeviceOrientationPortrait: case UIDeviceOrientationPortraitUpsideDown: rect = CGRectMake(0, 0, screenW, screenH); break; // 天地 case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: default: rect = CGRectMake(0, 0, screenW, screenH); break; } return rect; }
おそらくもっとエレガントな方法があると思うのですが。^^;
エレガントなやり方を御存知の方は教えてください。
No comments yet.