如何在swift中使用Textfield制作UITableview?

Zab*_*lah 14 cell uitableview uitextfield ios swift

我想在每个单元格中创建一个包含文本字段的表格视图,

我在swift文件中有一个自定义类:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的ViewController中我有

 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

}
Run Code Online (Sandbox Code Playgroud)

这很好用:

在此输入图像描述

但是当用户在文本字段中输入文本并按下按钮时,我想将每个文本字段的字符串存储在一个数组中.我试过了

text = cell.textField.text
println(text)
Run Code Online (Sandbox Code Playgroud)

但它没有打印就像它是空的

我怎样才能使它工作?

Fre*_*ust 14

在您的视图中,控制器成为UITextFieldDelegate

查看控制器

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)
}
}
Run Code Online (Sandbox Code Playgroud)

这将始终将textField中的数据附加到allCellsText数组.