2017-07-31 59 views
1

我想設置一個默認的項目視圖時加載的是這樣的:不能在UICollectionView選擇項編程

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 
} 

我忘了什麼嗎?

回答

5

selectItem(at:animated:scrollPosition:)

這種方法documentation不會導致調用任何選擇相關的委託方法。

這意味着您將不得不手動調用委託方法。

3

如果您以編程方式調用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))