在UIScrollView添加多个subview,但是subview一直不能显示出来。
约束如下:
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bgScrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bgScrollView)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[bgScrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bgScrollView)]];
[bgScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[topBannerScrollView]|" options:0 metrics:nil views:@{@"topBannerScrollView":self.topBannerScrollView}]];
[bgScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[classityCollectionView]|" options:0 metrics:nil views:@{@"classityCollectionView":self.classityCollectionView}]];
[bgScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[topBannerScrollView(==200)][classityCollectionView(==70)]" options:kNilOptions metrics:0 views:@{@"topBannerScrollView":self.topBannerScrollView, @"classityCollectionView":self.classityCollectionView}]];
观察它的图层显示Scrollable content size is ambiguous。
问题在于用autolayout给UIScrollView设约束没有设置它的contentsize而是根据subview的大小来自适应的,而上面代码subview的宽度却又是根据bgScrollView的边界来确定的,两者互相矛盾,所以必须先设置好subview的宽度:
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bgScrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bgScrollView)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[bgScrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(bgScrollView)]];
for (UIView *view in @[self.topBannerScrollView, self.classityCollectionView ])
{
[bgScrollView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:bgScrollView attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
}
[bgScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[topBannerScrollView]" options:0 metrics:nil views:@{@"topBannerScrollView":self.topBannerScrollView}]];
[bgScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[classityCollectionView]" options:0 metrics:nil views:@{@"classityCollectionView":self.classityCollectionView}]];
[bgScrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[topBannerScrollView(==200)][classityCollectionView(==70)]" options:kNilOptions metrics:0 views:@{@"topBannerScrollView":self.topBannerScrollView, @"classityCollectionView":self.classityCollectionView}]];
同样约束subview的宽度和bgScrollView相同,但@"H:|[subview]|"˙这样约束是有问题的(设置subview高度同理)。
以上,记开发过程中遇到的好几次坑~