UICollectionView如何准确获取contentSize高度

在tableView Cell中,嵌套了一个Collectionview。
它们都使用了AutoLayout布局,当对collectionview的Cell赋值后获取contentSize.height进行约束更新。
问题是height第一次获取时不是正确的值,而当我把Cell滑出屏幕后再回来,这个值才正确。这到底是为什么,我该怎么做?
以下是我在tableView Cell中的代码

func configModel(model: ResumeIntroduceModel?) {
        guard let model = model else { return }
        
        expLabel.text = model.experience
        typeLabel.text = model.typeStr
        homeLabel.text = model.hometown
        proLabel.text = model.profDegreeStr
        numberLabel.text = ("\(model.numberPeople ?? "0")人")
        
        tagDataArray = model.tags ?? []
        
        tagCollectionView.reloadData()
        tagCollectionView.layoutIfNeeded()
        
        let layoutContentHeight = tagCollectionView.collectionViewLayout.collectionViewContentSize.height
        print("layoutContentHeight:\(layoutContentHeight)")
        
        tagCollectionView.snp.updateConstraints { (make) in
            make.height.equalTo(layoutContentHeight)
        }
    }    

结果如下,第一次84是错误的,而滑出屏幕后再回来的47则是正确的
WX20191106-213947@2x.png

阅读 11.3k
1 个回答

这么简单的问题都没人回答吗? tableView reloadData是异步操作,
你执行tagCollectionView.reloadData()时,tagCollectionView实际上并未加载完所有item,所以contentSize拿到的也是错的
用以下伪代码试试

tagCollectionView.reloadData()
dispatch_async(dispatch_main_queue){
    let layoutContentHeight = 
    tagCollectionView.collectionViewLayout.collectionViewContentSize.height
        print("layoutContentHeight:\(layoutContentHeight)")
        
        tagCollectionView.snp.updateConstraints { (make) in
            make.height.equalTo(layoutContentHeight)
        }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题