无法以编程方式在 UICollectionView 中选择项目 [英] Can't select item in UICollectionView programmatically

查看:22
本文介绍了无法以编程方式在 UICollectionView 中选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to set a default item when the view is loaded this way:

override func viewDidLoad() {
   super.viewDidLoad()

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

}

我正在尝试在 viewDidAppear 方法中选择一个项目:

I'm trying to select an item in the viewDidAppear method:

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

但是 didSelectItemAt 方法没有像我需要的那样被触发.

But the didSelectItemAt method is not fired like I need.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
   //some config
}

我是不是忘记了什么?

推荐答案

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

didSelectItemAt is not called if you call selectItem programmatically. You should call the method manually after it.

self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom)
self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))

这篇关于无法以编程方式在 UICollectionView 中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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