高さと幅を正確に読み取るのに問題があります。そこで、状況をテストするために、この簡単で汚いアプリを作成しました。
コードは次のとおりです。
@interface wwfpViewController ()
@property (nonatomic, strong) UIView * box;
@property (nonatomic, strong) UILabel * info;
@end
@implementation wwfpViewController
@synthesize box,info;
- (void)viewDidLoad {
[super viewDidLoad];
box=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[box setBackgroundColor:[UIColor darkGrayColor]];
[box setAutoresizesSubviews:YES];
[box setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
info=[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 300)];
[info setTextColor:[UIColor whiteColor]];
[info setBackgroundColor:[UIColor blackColor]];
[info setLineBreakMode:NSLineBreakByWordWrapping];
[info setNumberOfLines:10];
[info setText:@"..."];
[self.view addSubview:box];
[box addSubview:info];
[self updateInfo];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updateView:)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];
}
- (void) updateInfo {
CGFloat selfHeight=self.view.frame.size.height;
CGFloat selfWidth=self.view.frame.size.width;
CGFloat boxHeight=box.frame.size.height;
CGFloat boxWidth=box.frame.size.width;
int deviceOrientation=[[UIDevice currentDevice] orientation];
int statusOrientation=[[UIApplication sharedApplication] statusBarOrientation];
NSString * str=[NSString stringWithFormat:@"[height x width] \nself: [%f x %f] \nbox: [%f x %f] \ndevice: %d status: %d",selfHeight,selfWidth,boxHeight,boxWidth,deviceOrientation,statusOrientation];
[info setText:str];
}
- (void) updateView: (NSNotification*) notify {
[self updateInfo];
}
@end
iPad でこれをテストすると、最初は縦向きモードで、情報ラベルは次のように報告します。
[height x width]
self: [1004.000000 x 768.000000]
box: [1004.000000 x 768.000000]
device: 0 status: 1
正解です!
iPad を横向きにすると、次のように表示されます。
[height x width]
self: [768.000000 x 1004.000000]
box: [1004.000000 x 768.000000]
device: 3 status: 3
実際の高さ×幅:748×1024
しかし、これをiPadで横向きにテストすると、情報ラベルは次のように報告します:
[height x width]
self: [1024.000000 x 748.000000]
box: [1024.000000 x 748.000000]
device: 0 status: 3
実際の高さ×幅:748×1024
次に、iPad を縦向きに回転すると、次のように表示されます。
[height x width]
self: [748.000000 x 1024.000000]
box: [748.000000 x 1024.000000]
device: 1 status: 1
実際の高さ×幅:1004×768
回転して横向きに戻すと、次の測定値が得られます。
[height x width]
self: [768.000000 x 1004.000000]
box: [1004.000000 x 768.000000]
device: 3 status: 3
実際の高さ×幅:748×1024
いずれの場合も、box
UIView は画面全体をカバーするため、向きの変更に正しく自動調整されます。これらの結果は、シミュレーターと実際の iPad でのテストから一貫しており、iPhone でも同様の経験があります。
この後、いくつか質問があります。
- 私は何を間違っていますか?
- の高さと幅が、見た目は同じに見えるのに
self.view
の高さと幅と異なるのはなぜですか?box
向きの変更に関係なく、画面またはビューの全体の高さと幅を正確に取得するにはどうすればよいですか。
- 最初に使用したときにゼロと報告されるため
[UIDevice ... orientation]
、完全に無視してそのまま使用する必要があり[UIApplication ... statusBarOrientation]
ますか?