R3ptor R3ptor - 2 years ago 55
iOS Question

Call content of UITextField from different class

My goal is that I can configure a label from a

inside a container view.

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

How can I get the text property from the
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() {

@IBOutlet weak var nameField: UITextField!

Answer Source

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



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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download