在视图控制器,如果使用的是故事板,连接(在我的例子collectionView
)使用IBOutlet中,(在我的例子collectionViewWidth
)集合视图宽度约束作为IBOutlet中和UICollectionView
作为IBOutlet中UICollectionviewFlowLayout
(collectionViewFlowLayout
在我的例子) 。可以用下面的同时改变它的集合视图帧和细胞:
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5, execute: {
self.width = 400
self.height = 400
self.collectionView.performBatchUpdates({
self.collectionViewFlowLayout.invalidateLayout()
self.collectionView.setCollectionViewLayout(self.collectionViewFlowLayout, animated: true)
}, completion: { _ in })
})
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5, execute: {
self.collectionViewWidth.constant = 50
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut,
animations: self.view.layoutIfNeeded, completion: nil)
})
你需要声明width
和height
VAR与例如100初始值类的属性。然后在上面的代码中进行更改。由于下面的实施,它成为可能。请注意,这需要您采用协议UICollectionViewDelegateFlowLayout
。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: width, height: height)
}
感谢您的帮助,但我有一个问题,现在我有不好的影响时,动画开始。 单元格内的图像变宽和变窄。 –
@ jimmy-gonçalves你能提供一些关于你如何建立细胞的更多信息吗?细胞大小如何变化? –
我把我的实际代码展示给你看,我的单元格实际上是用UICollectionFlowLayout中的方法设置的,它的大小为item的大小。 –