簡體   English   中英

iOS(Swift):給定UICollectionViewCell的UICollectionView

[英]iOS (Swift): UICollectionView for a given UICollectionViewCell

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

}

有什么方法可以從MyCell訪問MyViewController定義的collectionView實例嗎?

謝謝你的幫助。

你可以試試

 class MyCell: UICollectionViewCell, UICollectionViewDataSource {

    weak var outerCollectionView: UICollectionView!
 }

並將其設置在cellForRowAt

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

//

或者您可以嘗試像這樣投射superView

let collectionView = self.superView as! UICollectionView

以下評論中的建議:

extension UICollectionViewCell {

    /// The collection view that presents this cell.
    weak var collectionView: UICollectionView! {
        return self.superview as! UICollectionView
    }
}

試試下面的東西

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
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM