문제

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;
}

다른 팁

What is your desired effect? Same height, variable height, top margin, etc?

Do you want the label to always be that size? If so, you can turn off the auto resize

label.translatesAutoresizingMaskIntoConstraints = NO;

If you want the label to be the same height as your view...

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0];
[self.view addConstraint:constraint];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top