如何在Swift中使用Textfield制作UITableview?
我想在每个单元格中使用文本字段进行表格视图,
我有一个快速文件中的自定义类:
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 } }
然后在我的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 }
这很好:
但是当用户在文本字段中input文本并按下button时,我想将每个文本字段的string存储在数组中。 我曾尝试过
text = cell.textField.text println(text)
但它没有打印,就像是空的一样
我怎样才能使它工作?
在你的视图控制器成为一个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) } }
这将始终将textField中的数据附加到allCellsText数组。
创build一个variables
var arrayTextField = [UITextField]()
之后在你的func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{}
add
self.arrayTextField.append(textfield)
在返回单元格之前,在此之后使用显示值
for textvalue in arrayTextField{ println(textvalue.text) }
这个方法是初始化单元格,你没有模型来保存这个数据,所以
text = cell.textfield.text
没什么! 你可以在viewcontroller中初始化var textString
,一个inheritance的UITextFieldDelegate
optional func textFieldDidEndEditing(_ textField: UITextField) { textString = _textField.text } optional func textFieldShouldReturn(_ textField: UITextField) -> Bool{ return true }
和cell.textField.text = textString