How to make UITableview with Textfield in swift?

≯℡__Kan透↙ 提交于 2019-11-29 11:59:27

问题


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:

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?


回答1:


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.




回答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)
    }



回答3:


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



来源:https://stackoverflow.com/questions/31736884/how-to-make-uitableview-with-textfield-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!