调整 UICollectionView 大小

Sizing UICollectionView

所以这是我第一次使用 CollectionView,我有图像集合,我希望我的集合高度可以调整以显示所有图像,这样我就不必滚动查看其余图像了

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return list.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MycellCollectionViewCell
        cell.myimage.image = UIImage(named: list[indexPath.row]+".jpg")
        return cell
    }

调用reloadData()

后,可以使用performBatchUpdates(_:completion:)方法获取UICollectionView的高度
var height = CGFloat(0)
self.collectionView.reloadData()
self.collectionView.performBatchUpdates(nil) { (result) in
    if result {
        height = self.collectionView.contentSize.height
    }
}

之后您可以设置集合视图的框架高度:

collectionView.frame.size.height = height

或添加约束条件:

let height = NSLayoutConstraint(item: collectionView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
collectionView.addConstraint(height)

或者如果您已经从故事板或 XIB 设置了集合视图的高度,那么您可以将约束连接到您的代码并简单地更改常量:

collectionHeight.constant = height