簡體   English   中英

無法以編程方式在 UICollectionView 中選擇項目

[英]Can't select item in UICollectionView programmatically

當以這種方式加載視圖時,我試圖設置一個默認項:

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])
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM