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

drc*_*drc 0 uiview uilabel ios

上下文

  • 这是UIViewController一个UINavigationController堆栈内的
  • 在这里,UIViewControllerUILabel在(x,y)坐标(0,0)处以编程方式添加
  • 我已经尝试添加UILabel到self.view(这是在UIViewController中)或添加UILabel到a UIView,这UIView是self.containerView

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];
}
Run Code Online (Sandbox Code Playgroud)

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]
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

何时UILabel加入self.view

在此输入图像描述

何时UILabel加入self.containerView

问题

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

Mik*_*e M 5

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