Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...