ios - TableView 和 CollectionView : Adjust height of tableView and collectionView

标签 ios objective-c ios-autolayout

我有一个 View Controller ,其中有 tableView 和 Collection View 。我为 collectionView 和 tableView 设置了相同的高度。

前半部分是tableView,后半部分是collection view。我有一项服务电话对于 重载 tableview 和 collection view .

所以,我想根据其数据源调整 Collection View 的高度,然后根据 Collection View 自动调整表格 View 。

备注 - TableView 高度不依赖于它的数据源,只有 Collection View 高度取决于它的数据源。

// Collection View 流布局

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

//当前屏幕截图

enter image description here

最佳答案

如果您使用 auto layout那么你需要通过height constraints来管理它两者的tableView & collectionView &如果您使用框架,那么您需要根据单元格和单元格高度设置框架动态。

- (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];

    }



     }

enter image description here

tableView 的约束
  • 前导,尾随,顶部

  • collectioView 的约束
  • 前导、尾随、底部、高度

  • 现在再给出一个约束,
  • tableView 和 collectionView 之间的垂直空间 0

  • 现在从 Storyboard 中获取高度约束导出并对其进行管理。

    无需管理 tableHeight

    关于ios - TableView 和 CollectionView : Adjust height of tableView and collectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42432497/

    相关文章:

    ios - TableView 单元格中 UIButton 的自动布局不起作用

    iOS Swift3 使用键盘移动 Textfield 和 ContainerView

    ios - Azure 物联网通信

    iphone - 如何在uiwebview上添加捏和缩放-iPhone

    ios - 能运行成功但不能存档?

    objective-c - 使用前置摄像头Xcode的闪光效果

    objective-c - 应用程序 :openURL not triggered

    xcode - 优化 iPad 上多张图片的加载

    iphone - 如何制作可扩展的 UITableViewCell

    swift - heightAnchor.constraint 不改变 View 高度