我想在滚动视图中添加标签。这是在主控制器中完成的。但是,当我执行以下操作时,标签将覆盖滚动视图的内容。我希望标签完全位于顶部,然后是其余的滚动视图内容。
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, 80)];
label.backgroundColor = [UIColor greenColor];
label.text = @"Testing";
[self.scrollView addSubview: label];
[self.scrollView setNeedsDisplay];
答案 0 :(得分:1)
不幸的是,还有一些以编程方式执行此操作。我强烈建议您将此标签添加到您的xib或故事板中,而不是以编程方式执行此操作,但如果这不是任何理由,那么您只能执行一项操作。你需要迭代你的scrollView的子项并稍微向下推动每个下来为你的新标签腾出空间,然后在scrollView的顶部设置标签。
非常简单的例子,这可能无法完美运行,因此您需要根据需要调整它。
// Set the amount of y padding to push each subview down to make room at the top for the new label
CGFloat yPadding = 80.0f;
CGFloat contentWidth = CGRectGetWidth(self.contentView.frame);
UILabel* label = [[UILabel alloc] initWithFrame:(CGRect){CGPointZero, contentWidth, 44.0f}];
label.text = @"Testing";
// Iterate over each subview and push it down by the amount set in yPadding. Also, check for the subview with the lowest y value and set that as your labels y so that it is at the top of the scrollView.
for (UIView* subview in self.scrollView.subviews) {
CGRect subviewFrame = subview.frame;
CGFloat currentLabelY = CGRectGetMinY(label.frame);
// Set the labels y based off the subview with the lowest y value
if (currentLabelY == 0.0f || (currentLabelY > CGRectGetMinY(subviewFrame))) {
CGRect labelFrame = label.frame;
labelFrame.origin.y = subviewFrame.origin.y;
label.frame = labelFrame;
}
// Push the subview down by the amount set in yPadding
subviewFrame.origin.y += yPadding;
subview.frame = subviewFrame;
}
// Finally, add the label as a subView of the scrollView
[self.scrollView addSubview:label];
答案 1 :(得分:0)
您应该将标签添加为scrollview的子视图:
[self.scrollView addSubview:label]