Search code examples
iosswifttableviewtextfieldcustom-cell

Swift 3.0 Textfield in a TableViewCell not showing up


I am trying to display a textfield on a tableview using a custom cell. I think I have set up the delegation protocol properly, but when loaded, the tableview doesn't show the textfield. I have added a textfield into the customcell, set the class to CustomCell, and changed the identifier to "Cell", but I am not sure what else I am missing.

view controller with tableview:

@IBOutlet weak var tableView: UITableView! 


 override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Hello")

}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return data.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
    cell.cellDelegate = self
    cell.contentView.bringSubview(toFront: cell.textField)
    cell.textField.delegate = self as? UITextFieldDelegate
    cell.textField.text = "Test"

    return cell
}

func didPressTextField(indexPath: IndexPath) {
    print("textfield was tapped")
}

custom cell VC:

protocol CustomCellDelegate : class {
    func didPressTextField(indexPath: IndexPath)
}

class CustomCell: UITableViewCell {

    weak var cellDelegate: CustomCellDelegate?
    var indexPath: IndexPath!

    override func awakeFromNib() {
        super.awakeFromNib()
        self.cellDelegate = nil
        // Initialization code
    }

    @IBOutlet weak var textField: UITextField!
    @IBAction func textFieldWasTapped(_ sender: UITextField) {
        self.cellDelegate?.didPressTextField(indexPath: indexPath)
    }

Solution

  • Your data source is empty.

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // data is not containing any value
        return data.count
    }