R3ptor R3ptor - 6 months ago 8
iOS Question

Call content of UITextField from different class

My goal is that I can configure a label from a

UICollectionViewCell
inside a container view.

I have a view controller with an
UICollectionView
and if I double tap one of these cells a container view is opens. This is already working, but I have a
UITextField
inside the
ContainerViewController
which should update the
nameLabel
of the
ItemCell
.

How can I get the text property from the
containerController
to the
ItemCell func changeName()
?

class ItemCell: UICollectionViewCell {
@IBOutlet weak var nameLabel: UILabel!

func changeName() {
nameLabel.text = containerController.nameField.text
}
}


Obviously this function is not working.

var containerController = ContainerController()
class ContainerController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}

@IBOutlet weak var nameField: UITextField!
}

Answer

When you double tap the cell, pass a reference of the tapped cell to the ContainerController, then have the ContainerController instance call the changeName function on the cell. I would recommend mutating the changeName function to accept a String like so:

class ItemCell: UICollectionViewCell {

    @IBOutlet weak var nameLabel: UILabel!

    func changeName(newName: String) {
        nameLabel.text = newName
    }

}

UPDATE FOR AFTER THE CODE WAS GIVEN

One thing you could do is add a property to your ContainerController like so:

weak var textCell: ItemCell?

Then also change the method in ItemCell to take a String:

func changeName(newName: String) {
    nameLabel.text = newName
}

Then in your handleTap(_:) method, where you are retrieving the cell and calling openContainer(), change it to something like:

if let index = indexPath,
    let cell = ItemCollection.cellForItemAtIndexPath(index) as? ItemCell {
    container.textCell = cell
    openContainer()
} else {
    print("Could not find index path or cell")
}

Then in your ContainerController, once the text is entered call textCell?.changeName(_:) with the new text.

I also want to add that I do not recommend doing something like this. Ideally, the text the user enters in ContainerController would update the data source for the collection view then the app would reload that cell. With the way it is now, as soon as the cell is reused, the text will revert back to what the data source says. Just something to consider.