UILabel的位置使iPhone 4和iPhone 5兼容

时间:2013-04-14 14:56:14

标签: ios xcode iphone-5 iphone-4

为我的应用程序制作UILabel的简单代码是

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。

2 个答案:

答案 0 :(得分:1)

您可以在- (void)viewWillLayoutSubviews的{​​{1}}方法中以编程方式设置框架,也可以设置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

答案 1 :(得分: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];
相关问题