Ios swift:收藏中的图像
我在单元格中有图像的collectionView。我想在一些单元格中显示图像 我使用以下代码:Ios swift:收藏中的图像,ios,swift,Ios,Swift,我在单元格中有图像的collectionView。我想在一些单元格中显示图像 我使用以下代码: func numberOfSections(in collectionView: UICollectionView) -> Int { return 7 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 7
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MasterViewCell
if (indexPath.row == 2 && indexPath.section == 6) || (indexPath.row == 0 && indexPath.section == 0) {
cell.cover.isHidden = true
} else {
cell.cover.image = UIImage(named: "2.png")
}
}
但当我滚动我的collectionView图像时,它不会显示在某些不同的单元格中 请用此代码替换您的代码
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MasterViewCell
cell.cover.image = nil
if (indexPath.row == 2 && indexPath.section == 6) || (indexPath.row == 0 && indexPath.section == 0) {
cell.cover.isHidden = true
} else {
cell.cover.isHidden = false
cell.cover.image = UIImage(named: "2.png")
}
}
func collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MasterViewCell
if (indexPath.row == 2 && indexPath.section == 6) || (indexPath.row == 0 && indexPath.section == 0) {
cell.cover.isHidden = true
} else {
cell.cover.isHidden = false
cell.cover.image = UIImage(named: "2.png")
}
}
发生这种情况是因为集合视图单元格的可重用性。请用此代码替换您的代码 func collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MasterViewCell
if (indexPath.row == 2 && indexPath.section == 6) || (indexPath.row == 0 && indexPath.section == 0) {
cell.cover.isHidden = true
} else {
cell.cover.isHidden = false
cell.cover.image = UIImage(named: "2.png")
}
}
这是因为集合视图单元格的可重用性。所有其他答案都只是权宜之计。真正的问题是,您的
MasterViewCell
没有实现func prepareforuse()
,您应该在重用前准备单元格(在您的情况下,取消隐藏cover
视图)。如果实现自定义单元格,则始终需要重写此方法。请参见所有其他答案都只是权宜之计。真正的问题是,您的MasterViewCell
没有实现func prepareforuse()
,您应该在重用前准备单元格(在您的情况下,取消隐藏cover
视图)。如果实现自定义单元格,则始终需要重写此方法。请参见if语句使图像不会显示在某些单元格中。问题是什么还不太清楚。由于单元格重复使用,您需要确保在else
子句中设置cell.cover.ishiden=false,否则您的图像可能会由于以前使用的单元格中挂起的过时值而被隐藏。您应该在then子句中设置cell.cover.image=nil
。if语句使图像不会显示在某些单元格中。问题是什么还不太清楚。由于单元格重复使用,您需要确保在else
子句中设置cell.cover.ishiden=false,否则您的图像可能会由于以前使用的单元格中挂起的过时值而被隐藏。您应该在then子句中设置cell.cover.image=nil
。