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

问题描述

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

警报视图将以两个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,警报视图始终显示下一次而不是这次在上述代码内容中计算出的正确大小。

为什么它不直接显示正确大小的内容? 获得相同结果的其他解决方案在哪里?

解决方法

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

[self setNeedsLayout];
[self layoutIfNeeded];

将计算高度代码移至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);

}