[英]Swift: can't programmatically select MStickerView in 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))
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))
}
以上答案都不適用於我,因為我的collectionView
中IndexPath(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.