IOS/Objective-C: 子视图的子视图不显示

IOS/Objective-C: Subview of Subview not displaying

我正在尝试创建一个图表,其中 UIView 形式的条形图显示在背景 UIView 的顶部。我希望两者都显示在整个屏幕的 UIView 之上。我之前已经成功地做到了这一点,但是虽然我可以显示第一个视图,但我无法让我的代码显示栏。它可能与设置颜色有关吗?或者任何人都可以建议为什么第二个子视图不显示。

我的代码:

//Make background box:  
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat graphWidth = screenWidth-40;
    CGFloat graphHeight = 160;
      CGRect graphBounds =CGRectMake(20, 200, graphWidth, graphHeight);
    float tableStartY = graphBounds.origin.y;

    UIView *graphBox = [[UIView alloc] initWithFrame:graphBounds];
    graphBox.backgroundColor = [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:0.2]; graphBox.layer.borderWidth = 1;
    graphBox.layer.borderColor = [UIColor blueColor].CGColor;

//Make Bar

    CGFloat barWidth = 20;
    CGFloat barHeight = 100;
    CGRect aBar = CGRectMake(20, tableStartY+1, barWidth, barHeight);
    UIView *barView = [[UIView alloc] initWithFrame:aBar];
   barView.backgroundColor = [UIColor blueColor];
    barView.layer.borderWidth = 1;
    barView.layer.borderColor = [UIColor redColor].CGColor;

   // [graphBox addSubview:barView];
    [self.view addSubview: graphBox];

如果我运行上面的代码,它会显示graphBox。如果我将条形图作为子视图而不是 graphBox 直接添加到视图中,则会显示条形图。但是,如果我取消注释显示的行并先将 barView 添加到 graphBox,然后将 graphBox 添加到视图,则 barView 不会显示。

提前感谢您的任何建议。

如果我理解正确你需要做什么,你应该更换

CGRect aBar = CGRectMake(20, tableStartY+1, barWidth, barHeight);

CGRect aBar = CGRectMake(20, 1, barWidth, barHeight);

[编辑:显然取消注释 addSubview 行]

也许这是您发布的代码中的一个意外,但您已经特别注释掉 barView 将添加到屏幕的位置。

   // [graphBox addSubview:barView];

此外,如 所列,如果将 barView 添加到 graphBox,则偏移量不正确。如果您将其添加到 self.view,则您的偏移量是正确的。

因此,您有两个选择,具体取决于您在视图层次结构中所需的包含:

CGRect aBar = CGRectMake(20, 1, barWidth, barHeight);
// ...
[graphBox addSubview:barView];

CGRect aBar = CGRectMake(20, tableStartY+1, barWidth, barHeight);
// ...
[self.view addSubview: graphBox];
[self.view addSubview:barView];

请注意,在第二个选项中,为了使 barView 显示在 graphBox 之上,顺序很重要,因为它们将是兄弟姐妹。