Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UITableview with Textfield in swift?

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?

like image 778
Zablah Avatar asked Jul 31 '15 01:07

Zablah


People also ask

How do I populate UITableView?

There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.

What is UITableView in Swift?

A view that presents data using rows in a single column.

What is difference between Tableview and Collectionview?

When would you choose to use a collection view rather than a table view? Suggested approach: Collection views are there to display grids, but also handle entirely custom layouts, whereas table views are simple linear lists with headers and footers.


1 Answers

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.

like image 110
Fred Faust Avatar answered Nov 15 '22 20:11

Fred Faust