2013-05-26 3 views
2

내부에 컨테이너 뷰 (self.tagScrollContentView)가있는 스크롤보기가 있습니다. 스토리 보드에 있습니다. 그런 다음 버튼을 생성하고 제약 조건이있는 컨테이너 뷰에 프로그래밍 방식으로 배치합니다.iOS Autolayout : 제약 조건이있는 컨테이너 크기 조정

for(NSInteger i = 0; i < allTags.count; i++) { 
    UIButton *tagBt = [[UIButton alloc] initWithFrame:(CGRect){CGPointZero, tagSize.width + 30, 17}]; 
    [self.tagScrollContentView addSubview:tagBt]; 

    [constraintsArray addObject:[NSLayoutConstraint constraintWithItem:tagBt attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:nil multiplier:1.0 constant:tagSize.width + 30]]; 

    if(prevBtRow1) 
     [constraintsArray addObject:[NSLayoutConstraint constraintWithItem:tagBt attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:prevBtRow1 attribute:NSLayoutAttributeRight multiplier:1.0 constant:10.0]]; 
    else 
     [constraintsArray addObject:[NSLayoutConstraint constraintWithItem:tagBt attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.tagScrollContentView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:10.0]]; 

    [constraintsArray addObject:[NSLayoutConstraint constraintWithItem:tagBt attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.tagScrollContentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:7.0]]; 

    prevBtRow1 = tagBt; 
} 

[self.tagScrollContentView addConstraints:constraintsArray]; 
[self.tagScrollView layoutSubviews]; 

이 코드는 모든 너비에 따라 모든 단추를 배치합니다. 모두 잘 작동합니다. 그럼 내가 원하는 건 tagScrollContentView 모든 단추가이보기 안에 있고 범위를 벗어나지 않도록 확대하는 것입니다. 그런 다음 컨테이너보기와 동일한 올바른 내용 크기를 내 스크롤에 할당합니다. 스크롤이 제대로 작동하지 않습니다. 콘텐츠 크기가 컨테이너보기에 맞지 않습니다.

답변

1

중요한 문제는 최종 버튼에서 슈퍼 뷰로의 마지막 후행 제약 조건을 추가하지 않아서 contentSize이 설정되지 않는다는 것입니다. 난 당신이 'didn를 tagBt.translatesAutoresizingMaskIntoConstraints = NO; 라인을 가지고 가정

  1. : 당신은 마지막에 또 하나 개의 제약 조건을 추가 할 수 있습니다, 그리고 contentSize이 자동으로 조정됩니다

    for (NSInteger i = 0; i < allTags.count; i++) { 
        UIButton *tagBt = [[UIButton alloc] init]; 
        tagBt.translatesAutoresizingMaskIntoConstraints = NO; 
        [self.tagScrollContentView addSubview:tagBt]; 
    
        // add all of your constraints 
    
        prevBtRow1 = tagBt; 
    } 
    
    [constraintsArray addObject:[NSLayoutConstraint constraintWithItem:prevBtRow1 
                     attribute:NSLayoutAttributeTrailing 
                     relatedBy:NSLayoutRelationEqual 
                      toItem:self.tagScrollContentView 
                     attribute:NSLayoutAttributeTrailing 
                     multiplier:1.0 
                      constant:10.0]]; 
    
    [self.tagScrollContentView addConstraints:constraintsArray]; 
    

    는 무관 한 문제의 몇 가지가 있습니다 그것을 당신의 코드 샘플로 만드십시오.

  2. 제약 조건을 설정하려면 initWithFrame을 수행 할 필요가 없습니다. init이면 충분합니다.

  3. 버튼에 높이 제한을 추가하는 것이 좋습니다. 따라서 제약 조건이 명확 해집니다.

  4. 그런데, 당신은 슈퍼 뷰에 버튼 폭 제약을 추가하고 있습니다. 어느 쪽이든 작동하지만 일반적으로 가장 가까운 부모에 제약 조건을 추가하고 너비 제약 조건에 대해 버튼 자체가 아닌 수퍼 뷰를 추가합니다.

관련 문제