【问题标题】:Update UICollectionView height based on content根据内容更新 UICollectionView 高度
【发布时间】:2019-12-03 11:55:52
【问题描述】:

UICollectionView 高度未根据内容正确更新。如何更新高度

我的代码:

collectionViewArray.append(trimmedStrig!)
        DispatchQueue.main.async {
            if self.collectionViewArray.count == 1 {
                self.collectionViewHeight.constant = self.collectionView.contentSize.height + 50
                print(self.collectionViewHeight.constant)
            } else if self.collectionViewArray.count > 1 {
                self.collectionViewHeight.constant = self.collectionView.contentSize.height
                print(self.collectionViewHeight.constant)
            }
            self.collectionView.reloadData()
        }

//Fix collection view cell height and width
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: 100, height: 50)
}

创建第一个单元格时它不显示该单元格,这就是为什么我添加了 50 并且当单元格再次进入第二行时它没有更新高度,但是当在该时间高度中创建的第二行第二个单元格更新时。为什么我不知道?

【问题讨论】:

  • 尝试设置collectionview高度等于顶视图高度
  • @Alexandr Kolesnik,我不想固定到顶视图高度,因为它只是我 VC 中的一小部分
  • 但是,根据内容我正在更新我的 VC 高度,我有滚动视图
  • self.collectionViewHeight.constant = self.collectionViewArray.count * 50 self.view.layoutIfNeeded()。在这种情况下,不要忘记在更新约束后更新布局
  • 不,不更新高度

标签: ios swift xcode cocoa-touch uicollectionview


【解决方案1】:

试试这个可能对你有帮助

self.collView.reloadData()
self.collView.performBatchUpdates({}) { (complition) in
            self.cnsHeightCollView.constant = self.collView.contentSize.height
        }

【讨论】:

  • @iOS 填写正确请标记为正确答案
【解决方案2】:

在代码中添加这一行:-

collectionView.translatesAutoresizingMaskIntoConstraints = true
  • 例如
 override func viewDidAppear(_ animated: Bool)
 {
      super.viewDidAppear(animated)
      if self.collectionViewArray.count == 1 
      {
          self.collectionViewHeight.constant = self.collectionView.contentSize.height + 50
          print(self.collectionViewHeight.constant)
      }
      else if self.collectionViewArray.count > 1 
      {
           self.collectionViewHeight.constant = self.collectionView.contentSize.height
           print(self.collectionViewHeight.constant)
       }
            collectionView.translatesAutoresizingMaskIntoConstraints = true //Here
            self.collectionView.reloadData()            
   }

【讨论】:

  • 现在试试这个最新的
  • 将您的代码放入 viewDidAppear() 而不是 dispachQueue。
  • 在这里,当我单击 btn 单元格时,单元格将被装箱,这就是我使用队列的原因,我在 Btn 操作中编写您的代码。但是没用
猜你喜欢
  • 2019-03-04
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多