2017-10-28 129 views
1

在我的應用程序中,我使用的是UICollectionView。現在我想開發一個UIAlertController,點擊集合視圖中的任何單元格。 我開始用下面的代碼: 「GOT點擊」Swift:點擊UICollectionView的單元格並打開AlertViewController

extension HomeViewController: UICollectionViewDataSource { 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    … 
} 

// specify cells 
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    …. 
} 

// called when widget is moved 
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { 
     … 
} 

// called when clicked 
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    print("Got clicked!") 
} 

} 

但不知何故,從不打印。

+0

你設置委託和數據源? – ronatory

+0

不,我該怎麼做?對不起,我是初學者:D –

+0

@ AlexanderJeitler-Stehr,知道你已經開始iOS和學習Swift,這真是太好了。你只是錯過添加** UICollectionViewDelegate **到擴展。只需在** UICollectionViewDataSource **之後添加它,您就可以輕鬆前往。確保你已經將委託綁定到'HomeViewController'。快樂編碼:) –

回答

1

下一個嘗試:

extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate { 

} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    ... 
    cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(_:)))) 
} 

func tap(_ sender: UITapGestureRecognizer) { 

    let location = sender.location(in: self.collectionView) 
    let indexPath = self.collectionView.indexPathForItem(at: location) 

    if let index = indexPath {  
     print("Got clicked on index: \(index)!") 
    }   
} 
+0

感謝您的回答:)我現在將使用第二個版本。您能否告訴我如何將輕拍單元格的索引從輕擊功能傳遞到 func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell ? –

+0

你不需要這樣做。您在每個單元格中添加手勢識別器,並且當您選擇其中一個單元格時,在方法點擊(_ :)中獲得索引。如果你想改變你選擇的單元格,你可以使用下面的代碼來使用這個單元格:let cell = self.messageCollectionView.cellForItem(at:index) –

+0

謝謝! –

相關問題