How to make UITableview with Textfield in swift?

Zablah picture Zablah · Jul 31, 2015 · Viewed 32.4k times · Source

I want to make a table view with textfields in each cell,

I have a custom class in a swift file:

import UIKit

public class TextInputTableViewCell: UITableViewCell{

    @IBOutlet weak var textField: UITextField!
    public func configure(#text: String?, placeholder: String) {
        textField.text = text
        textField.placeholder = placeholder

        textField.accessibilityValue = text
        textField.accessibilityLabel = placeholder
    }
}

Then in my ViewController I have

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCellWithIdentifier("TextInputCell") as! TextInputTableViewCell

    cell.configure(text: "", placeholder: "Enter some text!")

     text = cell.textField.text

    return cell

}

That works well:

enter image description here

But when the user enters text in the textfield and press the button I want to store the strings of each textfield in an array. I have tried with

text = cell.textField.text
println(text)

But it prints nothing like if it was empty

How can I make it work?

Answer

Fred Faust picture Fred Faust · Jul 31, 2015

In your view controller become a UITextFieldDelegate

View Controller


class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

    var allCellsText = [String]()

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell

        cell.theField.delegate = self // theField is your IBOutlet UITextfield in your custom cell

        cell.theField.text = "Test"

        return cell
    }

    func textFieldDidEndEditing(textField: UITextField) {
        allCellsText.append(textField.text!)
        println(allCellsText)
    }
}

This will always append the data from the textField to the allCellsText array.