2014-02-10 71 views
-1

我想爲滾動視圖添加標籤。這是在主控制器中完成的。但是,當我執行以下操作時,標籤將覆蓋滾動視圖的內容。我希望標籤完全位於頂部,然後是剩餘的滾動視圖內容。將標籤添加到iOS中的滾動視圖中

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

你能更清楚地知道你想要什麼嗎? – Jack

+0

我希望標籤直接出現在滾動視圖的頂部... – Julia

回答

0

您應該添加標籤爲滾動視圖的子視圖:

[self.scrollView addSubview:label] 
1

不幸的是,有更多的編程這樣做一點。我強烈建議你將這個標籤添加到你的xib或storyboard中,而不是通過編程來完成,但如果這不是一個選擇,那麼你只能做一件事。你需要迭代你的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]; 
相關問題