Aaron Presley

← Writing
Registering Nib Text Field Event in Parent View

March 21, 2016

I've created a custom UiTableViewCell nib with a text field, and I've had a hell of a time figuring out how to register text changes in my parent view. I didn't find anything through Googling, so I figured I'd contribute the solution I figured out, using Swift:

CustomTableViewCell.swift

I created this file pretty simply. I just created a standard IBOutlet for the text field as normal.

import UIKit
class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var textField: UITextField!
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    
    @IBAction func namePrimaryActionTriggered(sender: AnyObject) {
        self.textField.endEditing(true)
    }
}

MyTableViewController.swift

Here's where it got fun. Firstly I extended UITextFieldDelegate on my class:

class MyTableViewController: UITableViewController, UITextFieldDelegate {

Next, I added this in the viewDidLoad() method:

self.customCell = NSBundle.mainBundle().loadNibNamed("CustomTableViewCell", owner: self, options: nil)[0] as! CustomTableViewCell
self.customCell.textField.delegate = self

For our cellForRowAtIndexPath we now use this variable:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.customCell
    
    cell.textField.text = "Some Text"
    
    return cell
}

We can now use the standard functions to detect changes in the nib's text field:

func textFieldDidEndEditing(textField: UITextField) {
    if textField == self.customCell.textField {
        debugPrint(textField)
    }
}

Not sure if this is the best way to go about it, as I'm just figuring out iOS. Use at your own risk!