为什么Y位置为0的UILabel不会位于屏幕顶部

时间:2013-08-20 21:26:24

标签: ios uiview uilabel

上下文

  • 这是UIViewController堆栈中的UINavigationController
  • 在此UIViewController中,我在(x,y)坐标(0,0)
  • 处以编程方式添加UILabel
  • 我已尝试将UILabel添加到self.view(这是在UIViewController中)或将UILabel添加到UIView,此UIView是self.containerView < / LI>

self.containerView已创建并通过以下代码添加到视图中:

- (void)addContainerView
{
    // Create a UIView with same frame as the screen bounds
    CGRect containerViewFrame = [[UIScreen mainScreen] applicationFrame];
    self.containerView = [[UIView alloc] initWithFrame:containerViewFrame];

    // Give the UIView a red background
    self.containerView.backgroundColor = [UIColor redColor];

    // Add the view
    [self.view addSubview:self.containerView];
}

通过以下代码添加UILabel

- (void)addTestLabel
{
    self.navigationController.navigationBarHidden = YES;
    CGRect frame = CGRectMake(0, 0, 100, 100);
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = @"this is a test";
    [self.view addSubview:label]; // OR [self.containerView addSubview:label]
}

enter image description here

UILabel添加到self.view

enter image description here

UILabel添加到self.containerView

问题

  • 为什么UILabel不在屏幕顶部,即使在状态栏后面?
  • 为什么yPos之间存在差异,具体取决于它是否已添加到self.viewself.containerView

1 个答案:

答案 0 :(得分:5)

更改标签的背景颜色,我想你会看到发生了什么。标签的高度为100像素,它在该空间内垂直居中。将高度更改为20或30并再次尝试。