ios – 如何在swift中使用Textfield进行UITableview?

前端之家收集整理的这篇文章主要介绍了ios – 如何在swift中使用Textfield进行UITableview?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在每个单元格中创建一个带有textfields的表视图,

我有一个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
    }
}

然后在我的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

}

这很好:

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

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数组.

原文链接:https://www.f2er.com/iOS/329457.html

猜你在找的iOS相关文章