首页 > 解决方案 > 从每个 TableViewCell 的 2 个文本字段中读取数据

问题描述

正如标题所说;我想从UITextField每个单元格的多个 s 中读取数据并将它们存储在一个数组中。我该怎么做?

我创建了一个CustomCell包含 2的子类UITextFields。P/S:小区的标识符也是CustomCell

非常感谢

class TableViewController : UITableViewController, UITextFieldDelegate {
var data = [input]()

@IBOutlet var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let customCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell

    customCell.input1.tag = indexPath.row
    customCell.input2.tag = indexPath.row
    customCell.input1.delegate = self
    customCell.input2.delegate = self

    return customCell
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data.count
}

@IBAction func addButton(_ sender: Any) {
    table.beginUpdates()
    table.insertRows(at: [IndexPath(row: data.count-1, section: 0)], with: .automatic)
    table.endUpdates()
}

func textFieldDidEndEditing(_ textField: UITextField) {
    let indexPath = IndexPath(row: textField.tag, section: 0)

    if let customCell = self.table.cellForRow(at: indexPath) as? CustomCell{

        let a = customCell.Credit.text!.isEmpty ? no:String(customCell.input1.text!)
        let b = customCell.letterGrade.text!.isEmpty ? no:String(customCell.input2.text!))

        inputRead.append(input(string1: a, string2: b))

    }

 @IBAction func foo(_ sender: Any) {
    if inputRead.count == 0{
        return
    }
    //the rest of implementation

}

自定义单元类:

Import UIKit

public class CustomCell: UITableViewCell {

    @IBOutlet weak var input1: UITextField!
    @IBOutlet weak var input2: UITextField!

}

标签: iosswiftuitableviewuitableviewrowaction

解决方案


在您的视图控制器中更新您的代码,如下所示。

将文本字段的委托自身分配给 ViewControllercellForRowAt

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  
    let customCell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

    customCell.input1.delegate = self
    customCell.input2.delegate = self

    return customCell
}

现在在您的视图控制器中实现了文本字段委托。

func textFieldDidEndEditing(_ textField: UITextField) {
    guard let jobTaskCell = textField.superview?.superview as? CustomCell else {
        return
    }

    if textField == jobTaskCell.input1 {
        // Get text from textfield and store in array
    } else if textField == jobTaskCell.input2 {
        // Get text from textfield and store in array
    }
}

注意:以下代码取决于如何在单元格中放置文本字段。因此,请确保您需要通过添加和删除superView来递归检查

guard let jobTaskCell = textField.superview?.superview as? CustomCell else {
    return
}

这仅仅意味着,仅当表格视图单元格内的文本字段没有任何额外视图时:

textField.superview = TableViewCell 的 contentView

textField.superview?.superview = TableViewCell

我希望这能解决您的问题。


推荐阅读