如何在swift中使用Textfield制作UITableview? [英] How to make UITableview with Textfield in swift?

查看:105
本文介绍了如何在swift中使用Textfield制作UITableview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每个单元格中创建一个包含textfields的表格视图,

I want to make a table view with textfields in each cell,

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

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
    }
}

然后在我的ViewController我有

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

}

效果很好:

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

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

我怎样才能使它工作?

推荐答案

在你的视图中控制器成为UITextFieldDelegate

In your view controller become a 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数组。

This will always append the data from the textField to the allCellsText array.

这篇关于如何在swift中使用Textfield制作UITableview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆