![](/img/trans.png)
[英]Swift - how automatically select cell when collectionView first loads up?
[英]Swift collectionview cant automatically select first cell when load
所以我有 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)
}
}
}
您必须从可见单元格中选择它。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let selectedIndex = collectionView.indexPathsForVisibleItems![0]
collectionView.selectItem(at: selectedIndex, animated: true, scrollPosition: .none)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.