The simple code for making an UILabel for my App is
UILabel *todaysGame = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 300, 250)];
todaysGame.text = @"Today's Game";
todaysGame.backgroundColor = [UIColor grayColor];
[self.view addSubview:todaysGame];
This is perfect for my iPhone 5 screen height but got messed up in iPhone 4 screen. I tried to read the iOS 6's auto layout feature but really did not understand how to do it. I do not want to use Storyboard or NIBs, I want to do that programmatically. How to position the UI elements that are both compatible with iPhone 4 and 5's screen heights.
I also tried to see if this helps instead of using numbers
screenBound = [[UIScreen mainScreen] bounds];
screenSize = screenBound.size;
screenWidth = screenSize.width;
screenHeight = screenSize.height;
and used "screenHeight" variable into the CGRectMake() method.
I am using Xcode 4.6 and iPhone 5 (iOS 6.1.3) and iPhone 4 for the same.
You can set frame programmatically in - (void)viewWillLayoutSubviews
method of your UIViewController
or set up autoresizingMask
property of view.
Set up frame:
- (void)viewWillLayoutSubviews {
if ([UIScreen mainScreen].bounds.size.height == 568) {
self.label.frame = CGRectMake(0, 0, 320, 100); // for iPhone 5
} else {
self.label.frame = CGRectMake(0, 0, 320, 60);
}
}
Or set up autoresizingMask
in - (void)viewDidLoad
:
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat height = self.view.bounds.size.height * 0.2 // 20% of parent view
self.label.frame = CGRectMake(0, 0, 320, height);
self.label.autoresizingMask = UIViewAutoresizingFlexibleHeight;
}