端末のLandscape, Portraitそれぞれで、Viewの配置を変更する方法のメモ
ポイント
・UIDeviceOrientationDidChangeNotification : 端末の向きが変わるのを検知
・UIDevice : デバイスのOrientationを取得
サンプルコード
1~10までの数字を幅一杯に表示させる。
端末の回転に合わせてリサイズ
#import “ViewController.h”
#import
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self ready];
}
– (void)viewDidAppear:(BOOL)animated
{
[self draw];
}
– (void)ready
{
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(orientationDidChange:) name: UIDeviceOrientationDidChangeNotification object: nil];
}
– (void)draw
{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
float dx;
if (orientation == UIDeviceOrientationLandscapeLeft ||
orientation == UIDeviceOrientationLandscapeRight) {
dx = self.view.frame.size.height / 12.0;
} else {
dx = self.view.frame.size.width / 12.0;
}
float margin = 2 * dx / 11;
for (int i=1; i<11; i++) {
float x = (i – 1) * (dx + margin) + margin * 1.0;
float y = dx;
UILabel *number = [[UILabel alloc] init];
number.layer.borderWidth = 5;
number.layer.borderColor = [UIColor yellowColor].CGColor;
number.layer.cornerRadius = 15;
number.frame = CGRectMake(x, y, dx, dx);
number.text = [NSString stringWithFormat:@”%d”, i];
number.font = [UIFont boldSystemFontOfSize:35];
number.textAlignment = UITextAlignmentCenter;
number.textColor = [UIColor brownColor];
[self.view addSubview:number];
}
}
– (void)orientationDidChange:(UIInterfaceOrientation)interfaceOrientation
{
for (UIView *v in self.view.subviews) {
[v removeFromSuperview];
}
[self draw];
}
– (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
– (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
@end