ios - Swift collectionview在加载时无法自动选择第一个单元格
问题描述
所以我有collectionview,我希望在加载视图时选择collectionview 单元格的第一个单元格,我尝试使用viewDidAppear 方法并且......不太好用。
因为我第一次尝试加载视图,第一个 collectionview 单元格没有被选中,但是当我回到前一个控制器然后点击回到 collectionview 控制器时,collectionview 的第一个单元格被选中。
我的意思是我不知道我必须来回走动,所以可以自动选择第一个单元格。
这是我的代码:
@IBOutlet weak var katalogColView: UICollectionView!
let indexPos = NSIndexPath(row: 0, section: 0) as IndexPath
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.katalogColView.selectItem(at: indexPos, animated: false, scrollPosition: [])
self.collectionView(katalogColView, didSelectItemAt: indexPos)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == katalogColView {
guard let cell = collectionView.cellForItem(at: indexPath) as? KatalogCell else {return}
cell.indicator.backgroundColor = #colorLiteral(red: 0.9916914105, green: 0.2737390399, blue: 0.284696877, alpha: 1)
cell.katalogText.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if collectionView == katalogColView {
guard let cell = collectionView.cellForItem(at: indexPath) as? KatalogCell else {return}
cell.indicator.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
cell.katalogText.textColor = #colorLiteral(red: 0.3950070143, green: 0.4162634611, blue: 0.4362195134, alpha: 1)
}
}
所以代码是当单元格被选中时,有一个 uiview 指示器,如果选中则为红色,如果未选中则为白色
我的代码有问题吗?我的意思是当然有问题,但谁能告诉我为什么它不起作用?
我的意思是,就像我说的那样,它只有在我回到前一个控制器时才有效,然后我回到那个collectionView控制器,它自动选择第一个单元格,但在我第一次加载控制器时没有自动选择。
谢谢
解决方案
在单元格类中添加这些行并尝试:
override var isSelected: Bool {
didSet {
if isSelected {
indicator.backgroundColor = #colorLiteral(red: 0.9916914105, green: 0.2737390399, blue: 0.284696877, alpha: 1)
katalogText.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
}else {
indicator.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
katalogText.textColor = #colorLiteral(red: 0.3950070143, green: 0.4162634611, blue: 0.4362195134, alpha: 1)
}
}
}
推荐阅读
- cordova - 离子:如何使用科尔多瓦插件网络服务器在混合应用程序中本地提供文件?
- java - 有条件地在打印 pdf 中显示文本
- django - 使用字段参数列表过滤 Django 模型
- java - 必须可解析为 Int - Java、Spring Boot
- pdf-generation - 我们可以使用 wkhtmltopdf 生成 PDF/A-3 文件吗
- reactjs - 在 npm run build 期间出现编译错误
- c# - 试图从 gridview 控件中获取数据键但得到“方法名称预期”编译错误,我的代码结构不正确吗?
- python - python numpy array reduction distance between elements
- r - R中时间序列的日期转换
- .net-core - Powershell,独立 OK,但脚本输出只是换行符