【发布时间】:2018-08-12 17:42:50
【问题描述】:
我正在尝试创建一个图表,其中 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 不会显示。
提前感谢您的任何建议。
【问题讨论】:
-
您似乎缺少对 bar 的强引用,它会立即被解除分配
-
@user6631314 我试试你的代码。它运作良好。请参阅屏幕截图ibb.co/jcPxwU。 barView 可以显示在屏幕上。
-
如前所述,barView 显示正确,但是通过将其分配为绝对坐标而不是相对坐标来计算其框架时出现错误,因此它被绘制在 graphBox 之外。您可以通过将 [graphbox addSubView:barView] 替换为 [self.view addSubView:barView] 并在 [self.view addSubView:graphBox] 之后移动它来查看它
标签: ios objective-c addsubview