我有一个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
}
}