Alessign
Alessign

Reputation: 788

Swift - Passing data from custom cell

I have UIViewController in which I've nested UICollectionView. For the UICollectionViewCell I created subclass "MyCell"

I have UITextField in each cell and want to pass the data from the text field back to parenting view controller to update label. The only way I found to update the label is to use NSNotificationCenter and call method to perform the changes and access the data from NSObject class. However, it returns nil value

ViewController:

var dataModel = DataModel() // NSObject class

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.updateResultLabel(_:)), name:"update", object: nil)
}

func updateResultLabel(notification: NSNotification){

    resultLabel.text = dataModel.cellData
    print(dataModel.cellData)
}

MyCell:

class MyCell: UICollectionViewCell {

    @IBOutlet weak var txtField: UITextField!

    @IBAction func updateLabel(){

        let cell: UICollectionViewCell = txtField.superview!.superview as! UICollectionViewCell
        let table: UICollectionView = cell.superview as! UICollectionView
        let textFieldIndexPath = table.indexPathForCell(cell)

        let dataModel = DataModel()
        dataModel.cellData = txtField.text!

        print("txtField: \(txtField.text), row: \(textFieldIndexPath?.row)")

        NSNotificationCenter.defaultCenter().postNotificationName("update", object: nil)
    }
}

The action is triggered directly from UITextField - valueChanged in storyboards

DataModel:

import Foundation

class DataModel: NSObject {

    var cellData: String?

}

"print" method from ViewController's method "updateResultLabel" shows "nil". I am obviously doing something wrong, possibly not initialising the string somewhere. Or there might be another way I didn't come across yet perhaps?

How can I pass data from "MyCell" to "ViewController" and update method please?

Thank you

Upvotes: 0

Views: 765

Answers (1)

Tob
Tob

Reputation: 943

I would use UITextfieldDelegate in the viewcontroller and set the delegate from the viewcontroller in the cells textfield.

Where you populate the cells you can write:

cell.txtField.delegate = self

You can now implement the delegate functions in your controller

Upvotes: 1

Related Questions