无法以编程方式选择 UI 中的项"联机视图"



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

override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.allowsSelection = true
self.collectionView.allowsMultipleSelection = true
}

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

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

但是didSelectItemAt方法并不像我需要的那样触发。

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

我是不是忘了什么?

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

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

来自selectItem(at:animated:scrollPosition:)的文档

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

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

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

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

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.activityCollectionView?.scrollToItem(at: IndexPath(row: 1, section: 0), at: UICollectionViewScrollPosition.right, animated: true)
}
//viewDidAppear is the key

就我而言,我需要将 Tamàs 和 iDev750 的答案结合起来:

DispatchQueue.main.async {
self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom)
self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
}

以上答案都不适用于我,因为我collectionViewIndexPath(item: 0, section: 0)单元格不可见,所以我的应用程序崩溃了。然后我通过滚动到 [0,0] 并等待collectionView完成其动画,然后手动调用委托方法didSelectItemAt选择项目来修复它。现在它完美运行。

示例代码:

/** scroll to cell that you want to select it */
layoutsCollectionView.selectItem(at: .init(item: 0, section: 0),
animated: true,
scrollPosition: .centeredHorizontally)
/** implement UIScrollViewDelegate in your view controller and call */
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
/** 
* here scroll animation finished thats mean your cell is visible
* now you can select your cell with delegate method
*/
layoutsCollectionView.delegate?.collectionView?(self.layoutsCollectionView, didSelectItemAt: [0,0])
}

自这篇文章以来的所有其他答案都没有说明放置集合视图选择方法的视图控制器方法。尝试将其放置在 viewDidSeem 方法中。

最新更新