UICollectionView-选择随机单元格 [英] UICollectionView - random cells are selected

查看:80
本文介绍了UICollectionView-选择随机单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个水平的UICollectionView,就像iOS中的水平日历. 分页已启用,但不允许MultipleSelection.

I have a Horizontal UICollectionView like the horizontal Calender in iOS. Paging is enabled but not allowsMultipleSelection.

self.allowsMultipleSelection = false
self.isPagingEnabled = true

每页只有5个单元格.

 let cellSize =    CGSize(width: self.view.frame.width / 5 , height: 60)

CollectionView的高度也是60.

CollectionView's height is also 60.

didSelectItemAt 将背景颜色更改为 .red ,将 didDeselectItem 重置为 .white .

didSelectItemAt change background color to .red and didDeselectItem resets it to .white.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    if let cell = cell {
        cell.backgroundColor = .red
    }
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    if let cell = cell {
        cell.backgroundColor = .white
    }
}

集合视图具有多个部分和行.如果我在第一个可见页面中选择一个单元格并滚动,则会在下一个可见页面中选择随机单元格.也就是说,下一页中的随机单元格为红色.我不希望这样.我想手动选择/更改单元格的颜色.

The collection view has multiple sections and rows. If I select a cell in the first visible page and scroll, random cells are selected in the next visible pages. That is to say random cells are red in the next pages. I do not want this to be so. I want to select/change color of cells manually.

我该如何解决?

推荐答案

不要忘记UICollectionView具有嵌入式重用机制,因此您应该直接在单元格类内部的方法"prepareToReuse"中取消选择单元格.

Don't forget that UICollectionView has embedded reusing mechanism, so you should deselect your cells in the method "prepareToReuse" directly inside the cell class.

这篇关于UICollectionView-选择随机单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆