为什么它不直接显示正确大小的内容?

Why does not it show content with the right size directly?

我想单击按钮然后显示警报视图。此警报视图将接收两个数组。

警报视图将按两个 UICollectionView 布局大小自行刷新。

[self.topCollectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:self.topSelectIndex inSection:0] animated:false scrollPosition:UICollectionViewScrollPositionBottom];
     
[self.bottomCollectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:self.bottomSelectIndex inSection:0] animated:false scrollPosition:UICollectionViewScrollPositionBottom];


 [self layoutIfNeeded];

  CGFloat topFloatHeight = self.topCollectionView.collectionViewLayout.collectionViewContentSize.height;
  CGFloat bottomFloatHeight = self.bottomCollectionView.collectionViewLayout.collectionViewContentSize.height;

   self.topCollectionHeightConstrait.constant = topFloatHeight;
    self.bottomCollectionHeightConstraint.constant = bottomFloatHeight;

//    CGFloat bigScrollViewHeight = self.bigScrollView.contentLayoutGuide.heightAnchor
    CGFloat catHeight = topFloatHeight + bottomFloatHeight + 200;
    CGFloat screenHeight = kScreenHeight - 180;
    if( catHeight < screenHeight) {
        self.scrollBoxHeightCont.constant = catHeight;
    }else {
        self.scrollBoxHeightCont.constant = screenHeight;
    }

   self.bigScrollView.contentSize = CGSizeMake(0, catHeight);

 [self.topCollectionView reloadData];
 
 [self.bottomCollectionView reloadData];

如您所见,关键代码是 self.bigScrollView.contentSize = CGSizeMake(0, catHeight);

代码更改了 bigScrollview 的 contentSize,提醒视图总是在下次而不是这次显示上面代码内容中计算的正确大小。

为什么不直接显示合适大小的内容? 哪里有其他解决方案可以得到相同的结果?

集合视图重新加载新数据后。 在客户视图展示之前,添加两行代码:

[自行设置NeedsLayout];
[自行布局IfNeeded];

将计算身高的代码移动到layoutSubviews方法中。

- (void)layoutSubviews {
[super layoutSubviews];


  CGFloat topFloatHeight = self.topCollectionView.collectionViewLayout.collectionViewContentSize.height;
  CGFloat bottomFloatHeight = self.bottomCollectionView.collectionViewLayout.collectionViewContentSize.height;

   self.topCollectionHeightConstrait.constant = topFloatHeight;
    self.bottomCollectionHeightConstraint.constant = bottomFloatHeight;

//    CGFloat bigScrollViewHeight = self.bigScrollView.contentLayoutGuide.heightAnchor
    CGFloat catHeight = topFloatHeight + bottomFloatHeight + 200;
    CGFloat screenHeight = kScreenHeight - 180;
    if( catHeight < screenHeight) {
        self.scrollBoxHeightCont.constant = catHeight;
    }else {
        self.scrollBoxHeightCont.constant = screenHeight;
    }


 self.bigScrollView.contentSize = CGSizeMake(0, catHeight);

}