我有一个UICollectionViewCell子类,包含在UICollectionView中,如下所示:

class MyCell: UICollectionViewCell {
}

class MyViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet public var collectionView: UICollectionView!

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as? MyCell else { fatalError("Unexpected indexPath") }
        return cell
    }

}

有没有办法从collectionView中访问MyViewController中定义的MyCell实例?
谢谢你的帮助。

最佳答案

试试下面这样的

protocol MyCellDelegate {
    func reloadData()
}
class MyCell: UICollectionViewCell {
    var delegate: MyCellDelegate!
}

class MyViewController: UIViewController {
    //lets say this is your view controller and datasource
}

extension MyViewController: UICollectionViewDataSource {
    //Methods are not implemeted here
    //But you can set the delegate of the cell in cellForRowAtIndex method which is your view controller
}

extension MyViewController: MyCellDelegate {
   func reloadData() {
        //Here you reload the collection view
   }
}

10-08 18:31