经过多次实验和阅读,我找到了答案.在某种构造函数中加载.xib(在我的例子中是一个类级别的方法),你必须确保调用[view setTranslatesAutoresizingMaskIntoConstraints:NO];例如,我已经完成了以下操作:
+ (InputView *)inputViewWithHeader:(NSString *)header subHeader:(NSString *)subHeader inputValidation:(ValidationBlock)validation
{
InputView *inputView = [[[NSBundle mainBundle] loadNibNamed:@"InputView" owner:self options:nil] lastObject];
if ([inputView isKindOfClass:[InputView class]]) {
[inputView setTranslatesAutoresizingMaskIntoConstraints:NO];
[inputView configureWithHeader:header subHeader:subHeader inputValidation:validation];
[inputView layoutIfNeeded];
[inputView invalidateIntrinsicContentSize];
return inputView;
}
return nil;
}
那么有必要重写layoutSubviews和intrinsicContentSize.覆盖的layoutSubviews允许我设置我的标签的preferredMaxLayoutWidth,而覆盖innerContentSize允许我根据约束和子视图来计算大小!这是我的实现:
- (void)layoutSubviews {
[super layoutSubviews];
self.subHeaderLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds);
[super layoutSubviews];
}
- (CGSize)intrinsicContentSize {
CGFloat height = self.headerView.bounds.size.height;
height += self.headerInputSpacer.constant;
height += self.inputField.bounds.size.height;
height += self.inputButtonSpacer.constant;
height += self.buttonView.bounds.size.height;
CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width - 20,height);
return size;
}
我相信有办法改进这个,或者更好的方法来实现,但现在它至少是正确的大小!对于不应有用户定义的框架的视图非常有用.