How to make UITableview with Textfield in swift?
Asked Answered
A

4

15

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?

Alisa answered 31/7, 2015 at 1:48 Comment(1)
already answered in #7344747Star
P
16

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.

Plentiful answered 31/7, 2015 at 2:33 Comment(4)
This works! But how can I append textfield.text to the array when the button is pressed? I tried putting: allCellsText.append(textField.text) println(allCellsText) inside the buttonPressed function but it doesnt identify the textfieldAlisa
That can't be done using it with the textField delegate, though you could set some type of condition on your data with the button, or copy the data to a different array.Plentiful
@thefredelement In class ViewController I have created an instance of TextInputTableViewCell and in ViewDidAppear, I am trying to assign the data from UserDefaults to var textField from TextInputTableViewCell, but the assignment fails, unexpectedly found nil while unwrapping an Optional valueHermeneutics
But won't this just keep on appending to allCellsText whenever textFieldDidEndEditing is called?Enesco
T
2

this method is init the cell,u have not model to save this datas,so

text = cell.textfield.text

is nothing! you can init var textString in viewcontroller,an inherit UITextFieldDelegate

optional func textFieldDidEndEditing(_ textField: UITextField)
{
     textString = _textField.text
}
optional func textFieldShouldReturn(_ textField: UITextField) -> Bool{
    return true
}

and cell.textField.text = textString

Titustityus answered 31/7, 2015 at 2:0 Comment(0)
D
2

create a variable

var arrayTextField = [UITextField]()

after this in your func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{} add

self.arrayTextField.append(textfield)

before returning cell, after this to display the values using

for textvalue in arrayTextField{
        println(textvalue.text)
    }
Deflection answered 16/7, 2016 at 10:38 Comment(2)
Wouldn't this cause issues for table rows that might become recycled, or does it retain the memory location of the cell even if you scroll out of view?Shipentine
This is a good idea, however as @JoseRamirez pointed out, if you scroll the view, your cellForRowAtIndexPath will append another textview.Dyspnea
D
-1

So here is a way to do it using the suggestion of having a textfield array. It uses the tag of the textfield to ensure it does not get added multiple times when you scroll.

// Assumes that you have a label and a textfield as a part of you tableViewCell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? BodyStatsTableViewCell else {
        return UITableViewCell()
    }
    cell.rowLabel.text = bodyTableArray[indexPath.row].rowTitle
    let tagValue = indexPath.row + 100
    var newRow = true
    for textvalue in arrayTextField{
        if textvalue.tag == tagValue {
            newRow = false
        }
    }
    if newRow {
        cell.rowTextField.tag = tagValue
        self.arrayTextField.append(cell.rowTextField)
        cell.rowTextField.text = bodyTableArray[indexPath.row].rowValue
    }
    return cell
}

// And then you cam get the values when you want to save with where tag - 100 will be the array index value to update

for textvalue in arrayTextField{ print(textvalue.text) }

Dyspnea answered 7/2, 2020 at 15:52 Comment(2)
After scrolling, this may have different UITextFields in the arrayTextField than are visible in the UI. Also, the other solutions to the question are working correctly without having to resort to this kind of hacks.Roommate
@fishinear, thanks, not sure where I was going with thisDyspnea

© 2022 - 2024 — McMap. All rights reserved.