无法以编程方式在UICollectionView中选择项目

Dav*_*que 6 ios uicollectionview uicollectionviewcell swift

我正在尝试以这种方式加载视图时设置默认项:

override func viewDidLoad() {
   super.viewDidLoad()

   self.collectionView.delegate = self
   self.collectionView.dataSource = self
   self.collectionView.allowsSelection = true
   self.collectionView.allowsMultipleSelection = true

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试选择viewDidAppear方法中的项目

override func viewDidAppear(_ animated: Bool) {
    DispatchQueue.main.async(execute: {
        self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: UICollectionViewScrollPosition.bottom)
    })
}
Run Code Online (Sandbox Code Playgroud)

但是这种didSelectItemAt方法并没有像我需要的那样被解雇.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
   //some config
}
Run Code Online (Sandbox Code Playgroud)

我忘记了什么吗?

mag*_*zbc 14

文档selectItem(at:animated:scrollPosition:)

此方法不会导致调用任何与选择相关的委托方法.

这意味着您必须手动调用委托方法.


Tam*_*gel 11

didSelectItemAt如果以selectItem编程方式调用,则不会调用.你应该在它之后手动调用该方法.

self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom)
self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
Run Code Online (Sandbox Code Playgroud)

  • 调用 self.collectionView.reloadItems(at: [indexPath]) 可能会更好,因为屏幕外的单元格可能会使您的应用程序崩溃。但这取决于你的细胞的逻辑 (2认同)

iDe*_*750 11

let indexPath = IndexPath(item: 0, section: 0)
DispatchQueue.main.async {
   self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .left)
}
Run Code Online (Sandbox Code Playgroud)

这是对我有用的解决方案。希望这会帮助你。