2013-04-14 52 views
0

用於製造的UILabel我的應用程序的簡單代碼位置,使爲iPhone 4和iPhone兼容5

UILabel *todaysGame = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 300, 250)]; 
todaysGame.text = @"Today's Game"; 
todaysGame.backgroundColor = [UIColor grayColor]; 
[self.view addSubview:todaysGame]; 

這是適合我的iPhone 5屏幕的高度,但在iPhone 4弄亂屏幕。我試圖閱讀iOS 6的自動佈局功能,但真的不知道該怎麼做。我不想使用Storyboard或NIB,我想以編程方式進行。如何定位兼容iPhone 4和5屏幕高度的UI元素。

我也試圖看到如果這有助於使用數字

screenBound = [[UIScreen mainScreen] bounds]; 
screenSize = screenBound.size; 
screenWidth = screenSize.width; 
screenHeight = screenSize.height; 

和使用的「screenHeight」可變進CGRectMake()方法代替。

我使用的是Xcode 4.6和iPhone 5(iOS 6.1.3)和iPhone 4。

回答

1

您可以以編程方式設置框架- (void)viewWillLayoutSubviews您的UIViewController方法或設置autoresizingMask屬性的視圖。

設置框:

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

或者autoresizingMask- (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; 
} 
+0

哇,真棒,爲我工作。這很簡單,謝謝你:-) – jeewan

0

什麼是你想要的效果?相同的高度,可變的高度,上邊距等?

您是否希望標籤始終具有該尺寸?如果是這樣,你可以關掉自動調整

label.translatesAutoresizingMaskIntoConstraints = NO; 

如果你想在標籤設置爲相同的高度,你的看法......

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0]; 
[self.view addConstraint:constraint]; 
+2

需要注意的是'NSLayoutConstraint'僅在iOS 6以後纔可用 –