滚动集合视图时,cellForItemAt indexPath 会出现问题
cellForItemAt indexPath gives an issue when collection view is scrolled
我有一个包含一个部分的 collectionView,部分中的 numberOfItems 是 100。我正在根据 cellforItemAt indexPath 方法中的条件加载集合视图,即
if (indexPath.row % 5 == 0) {
cellWidth = 100
} else {
cellWidth = 50
}
这会正确加载集合视图,但是当我滚动时,集合视图无法正常工作。
我期待的是图 1
图 2 是我在滚动集合视图时得到的。
tableView 中也出现了滚动问题,CellView 中有一个名为 prepareForReuse() 的函数可以用来解决此问题;在这个函数中,你应该重置 cellWidth 的值,因为有时在滚动 collectionView 时,变量会变得混乱
在您的 CollectionViewCell 中,您可以像这样调用此函数
override func prepareForReuse() {
super.prepareForReuse()
cellWidth = nil
}
了解您的单元格是自定义单元格还是普通 UICollectionViewCell 会很有帮助
因为单元格是可重复使用的,所以我建议您在
中更改宽度,而不是像这样给出宽度值
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.row % 5 == 0 {
return CGSize(width: 100, height:10)
}else {
return CGSize(width:50, height:10
}
}
要确定单元格内内容的宽度,我建议使用 sizeForItemAtIndexPath
,如下所示:
首先让你的控制器符合协议UICollectionViewDelegateFlowLayout
并实现方法:
extension YourViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.row % 5 == 0 {
return CGSize(width: 100, height: YourCellHeight)
} else {
return CGSize(width:50, height: YourCellHeight)
}
}
}
我有一个包含一个部分的 collectionView,部分中的 numberOfItems 是 100。我正在根据 cellforItemAt indexPath 方法中的条件加载集合视图,即
if (indexPath.row % 5 == 0) {
cellWidth = 100
} else {
cellWidth = 50
}
这会正确加载集合视图,但是当我滚动时,集合视图无法正常工作。
我期待的是图 1 图 2 是我在滚动集合视图时得到的。
tableView 中也出现了滚动问题,CellView 中有一个名为 prepareForReuse() 的函数可以用来解决此问题;在这个函数中,你应该重置 cellWidth 的值,因为有时在滚动 collectionView 时,变量会变得混乱
在您的 CollectionViewCell 中,您可以像这样调用此函数
override func prepareForReuse() {
super.prepareForReuse()
cellWidth = nil
}
了解您的单元格是自定义单元格还是普通 UICollectionViewCell 会很有帮助
因为单元格是可重复使用的,所以我建议您在
中更改宽度,而不是像这样给出宽度值 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.row % 5 == 0 {
return CGSize(width: 100, height:10)
}else {
return CGSize(width:50, height:10
}
}
要确定单元格内内容的宽度,我建议使用 sizeForItemAtIndexPath
,如下所示:
首先让你的控制器符合协议UICollectionViewDelegateFlowLayout
并实现方法:
extension YourViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.row % 5 == 0 {
return CGSize(width: 100, height: YourCellHeight)
} else {
return CGSize(width:50, height: YourCellHeight)
}
}
}