2014-02-10 2 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

당신은있는 ScrollView의 서브 뷰로 레이블을 추가해야합니다 :

[self.scrollView addSubview:label] 
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]; 
관련 문제