하위 뷰를 제거하면 해당 하위 뷰와 관련된 모든 제약 조건이 손실됩니다. 나중에 하위 뷰를 추가해야하는 경우 해당 하위 뷰에 제약 조건을 다시 추가해야합니다.
일반적으로 내 사용자 지정 하위보기에서 제약 조건을 만듭니다. 예 :
-(void)updateConstraints
{
if (!_myLayoutConstraints)
{
NSMutableArray *constraints = [NSMutableArray array];
// Create all your constraints here
[constraints addWhateverConstraints];
// Save the constraints in an ivar. So that if updateConstraints is called again,
// we don't try to add them again. That would cause an exception.
_myLayoutConstraints = [NSArray arrayWithArray:constraints];
// Add the constraints to myself, the custom subview
[self addConstraints:_myLayoutConstraints];
}
[super updateConstraints];
}
updateConstraints
은 Autolayout 런타임에 의해 자동으로 호출됩니다. 위의 코드는 사용자 정의 하위 클래스 UIView
에 있습니다.
Autolayout으로 작업 할 때 프레임 크기를 건드리지 않으셔도됩니다. 대신 제약 조건을 updateConstraints
으로 업데이트하면됩니다. 또는 제약 조건을 설정하여 필요가 없도록 설정할 수도 있습니다.
그 주제에 대한 내 대답을 참조하십시오 :
Autolayout UIImageView with programatic re-size not following constraints
당신은 초기 프레임을 설정할 필요가 없습니다. initWithFrame
을 사용하는 경우 CGRectZero
으로 설정하면됩니다. 제약 조건은 사실 이어야합니다. - 크기가 얼마나 커야하는지 또는 런타임이 그 크기를 추론 할 수있는 다른 관계인지를 자세히 설명해야합니다.
예를 들어, 시각 형식이 : @"|-[myView]-|"
인 경우, 수평 치수에 필요한 모든 것입니다. Autolayout은 myView
크기가 |
으로 표시되는 부모 superview
의 경계까지 알 수 있습니다. 그것은 꽤 멋지다.
감사합니다. 멋지다. 내가 코코아에 대해 물어 보았지만 코코아 터치가 아니라 다른 사람에게 알려주는 API는 (같은 Peter Ammon ofApple의 설명처럼) 동일하거나 거의 동일합니다. 두 세계에서의 접근 방식은 동일해야합니다. – uchuugaka
네, 미안 해요. 좋은 지적 –
[문서] (https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/updateConstraints)는 ** 중요 ** 구현에서 마지막 단계로'[super updateConstraints]'를 호출하십시오. 당신의 방법이 끝날 때가 아니라 처음에 가야합니다. – Eric