简体   繁体   中英

Passing data from Collection View Cell to View Controller

Here is the UICollectionViewCell class:

class ViewCell: UICollectionViewCell {

@IBOutlet weak var lblOutlet: UILabel!
@IBOutlet weak var contentViewOutlet: UIView!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

public var dismiss: (()-> Void)? = nil

@IBAction func btnBack(_ sender: UIButton) {
    self.dismiss?()
}
}

And here is the necessary code scope for the ViewController Class:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell: ViewCell = // Your code to dequeue cell
    cell.dismiss = { [weak self] in
         //??????
    }
}

For example, let's assume that I have to pass this data sender.titleLabel?.text in to ViewController. So how can I add this parameter(sender.titleLabel?.text) to this code:

public var dismiss: (()-> Void)? = nil 

and How can I read this data in View Controller in below scope:

cell.dismiss = { [weak self] in
     //Here.
}

You can try

public var dismiss: ((String)-> Void)? = nil 

and

self.dismiss?(sender.titleLabel!.text)

Then

cell.dismiss = { [weak self] str  in
    //Here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM