Jules
Jules

Reputation: 7766

How do I gain access to a custom UITableViewCell from textFieldDidEndEditing?

I have a custom UITableViewCell where I've added a UITextField, I'd like to perform some validation on the textfield and set a hasError property on the cell to maybe add a error label to the cell and change the textfield back color.

I'm not using a storyboard and creating my custom cell / UITableViewCell programatically.

I'm using textFieldDidEndEditing in my UIViewController to detect text changes and have no access to the cell, to set my hasError property.

I guess I could loop around the views / textfields by a tag to field the textfield then gain it's parent.

Or maybe I should implement my own version of textFieldDidEndEditing which then fires another event which has the cell and the textfield as parameters.

But I'm not sure if that's the best approach or how to fire an event.

Upvotes: 0

Views: 190

Answers (1)

Glenn Posadas
Glenn Posadas

Reputation: 13291

You can use Protocol. https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/Protocol.html

A simple example:

cellForRow

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ....
    cell.delegate = self
    return cell
}

Your UITableViewCell subclass:

class Cell: UITableViewCell, UITextFieldDelegate {

    // MARK: - Properties

    weak var delegate: CellDelegate?
    ....

    // MARK: - Functions

    func textFieldDidEndEditing(_ textField: UITextField) {
        self.delegate?.cell(self, textFieldDidEndDiting: textField)
    }
}

Your Protocol

protocol CellDelegate: class {
    func cell(_ cell: Cell, textFieldDidEndDiting textField: UITextField)
}

Then finally, conform your controller to that protocol like so:

class ViewController: UIViewController, CellDelegate {

    func cell(_ cell: Cell, textFieldDidEndDiting textField: UITextField) {

    }

}

Upvotes: 1

Related Questions