Home > Net >  Update UILabel on value change of a UITextField in a generated custom UITableViewCell
Update UILabel on value change of a UITextField in a generated custom UITableViewCell

Time:10-21

I have multiple custom UITableViewCells, each containing a UITextField. On value change of any of those text fields, I want to update a UILabel elsewhere in the view. How do I do that?

The label displays an aggregate of all the text fields' values. The number of cells is dynamic.

(I guess that's very easy, but I'm new to Swift development. My first attempt was to add an @IBAction to the cell class definition, but I got stuck on trying to get a reference to the label.)

Edit: The accepted answer is absolutely fine and works. I also recommend checking the solution recommended by DonMag in the comments section as it may be better in the long run, although it seems more difficult to implement for a beginner.

CodePudding user response:

assuming that the datasource of the UITableView that you are using is a UIViewController, I think that you should set the delegate property of your UITextField in the tableView(cellForRow:at:) method of the UIViewController. For example:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "myCellReusableId") as! MyCell
            cell.myTextField.delegate = self
            return cell
}

Then you have to conform to UITextFieldDelegate protocol and implement the textFieldDidEndEditing(_ textField:, reason:) method. This method will be called when the user ends editing. For example:

extension MyViewController: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
        let text = textField.text
        //Here you are in the UIViewController so you have the reference to the UILabel you want to update
    }
    
    
}
  • Related