TableView和CollectionView:调整tableView和collectionView的高度

TableView and CollectionView: Adjust height of tableView and collectionView

我有一个视图控制器,其中有 tableView 和 collection view。我为 collectionView 和 tableView 设置了相同的高度。

上半部分是 tableView,下半部分是集合 view.I 有 一个服务调用 重新定位 tableview 和集合视图

所以,我想根据其数据源调整集合视图的高度,然后表视图会根据集合视图自动调整。

注意- TableView 高度不依赖于它的数据源,只有集合视图高度依赖于它的数据源。

//集合视图流布局

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
  return CGSizeMake((self.collectionView.frame.size.width/2)-4, 68);
}

//当前屏幕截图

UICollectionView 和 UITableView 是 UIScrollView 的子视图,可以使用 setContentOffset 实现。

首先,添加观察者获取collectionView的contentOffset。然后,使用 setContentOffset 到 tableView。

如果您使用的是 auto layout,那么您需要通过 tableViewcollectionViewheight constraints 来管理它,如果您使用的是框架,那么您需要设置根据单元格和单元格高度的框架动态。

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

[self adjustCollectionViewHeightForCollection:collectionView withNumberOfCollectionCells:dynamicCollectionCellArray.count];

  return dynamicCollectionCellArray.count;
}


    -(void) adjustCollectionViewHeightForCollection:(UICollectioView *)collectionView withNumberOfCollectionCells:(NSUInteger)numberOfCollectionCell{
      //Adjust CollectionView height constraint

    int height = kConstantCollectionCellHeight * (numberOfCollectionCell /2 + numberOfCollectionCell %2);

    if(height < self.view.frame.height/2){

 self.collectionViewHeightConstraint.constant = kConstantCollectionCellHeight * (numberOfCollectionCell /2 + numberOfCollectionCell %2);   //(Make sure height constant manage properly coz here you are managing items in the collectionView so there are two items at each row)

         [self.yourCollectionView layoutIfNeeded];
         [self.yourCollectionView setNeedsLayout];

    }else{
self.collectionViewHeightConstraint.constant = self.view.frame.height/2;   //(Make sure height constant manage properly coz here you are managing items in the collectionView so there are two items at each row)

         [self.yourCollectionView layoutIfNeeded];
         [self.yourCollectionView setNeedsLayout];

    }



     }

tableView 的约束条件

  • 前导、尾随、顶部

collectionView 的约束条件

  • 前导、尾随、底部、高度

现在再给一个约束,

  • 垂直 space 在 tableView 和 collectionView 之间 0

现在从情节提要中获取高度限制出口并对其进行管理。

无需管理tableHeight