如何从 Swift 的 UITableView 中嵌入的文本字段检索数据?

How can I retrieve the data from a text field that is embedded in a UITableView in Swift?

我一直在尝试在 UITableView 中创建一个提交表单(即每行都有一个文本字段的 table 视图),但无法检索用户输入来自 table 视图中以编程方式生成的文本字段。

这是目前的代码:

class VC12: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

@IBOutlet weak var VC12TableView: UITableView!

var VC12Inputs = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.VC12TableView.dataSource = self

    VC12Inputs.append("Input 1")
    VC12Inputs.append("Input 2")
    VC12Inputs.append("Input 3")
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = VC12TableView.dequeueReusableCell(withIdentifier: "cell") ?? makeCell()
    let textField = cell.viewWithTag(1) as! UITextField
    let row = indexPath.row

    textField.placeholder = VC12Inputs[row]

    return cell
}

func makeCell() -> UITableViewCell {
    let textField = UITextField(frame: CGRect.zero)

    textField.tag = 1
    [textField].forEach {
        [=11=].translatesAutoresizingMaskIntoConstraints = false
        [=11=].borderStyle = .roundedRect
    }

    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    [textField].forEach { cell.contentView.addSubview([=11=]) }

    let views = ["textField": textField]
    let c1 = NSLayoutConstraint.constraints(withVisualFormat: "H:[textField]", options: .alignAllLastBaseline, metrics: nil, views: views)
    let c2 = NSLayoutConstraint(item: textField, attribute: .left, relatedBy: .equal, toItem: cell.layoutMarginsGuide, attribute: .left, multiplier: 1, constant: 0)
    let c3 = NSLayoutConstraint(item: textField, attribute: .centerY, relatedBy: .equal, toItem: cell.contentView, attribute: .centerY, multiplier: 1, constant: 0)
    let c4 = NSLayoutConstraint(item: textField, attribute: .width, relatedBy: .equal, toItem: cell.contentView, attribute: .width, multiplier: 0.9, constant: 0)
    let c5 = NSLayoutConstraint(item: textField, attribute: .height, relatedBy: .equal, toItem: cell.contentView, attribute: .width, multiplier: 0.09, constant: 0)

    NSLayoutConstraint.activate(c1 + [c2, c3, c4, c5])

    return cell
}

@IBAction func VC9Done(_ sender: Any)
{

}

这会生成一个包含 3 个文本字段的标准 table 视图;每行一个,即像这样:https://i.stack.imgur.com/JOwO0.png

但是,当用户点击 "Done" 时,我不确定如何检索用户在文本字段中输入的文本。关于解决此问题的最佳方法有什么想法吗?

此处显示的代码基于代码不同 (https://whosebug.com/users/2538939/code-different?tab=profile) from the question (Adding a text field to a UITableview Cell) by B B (https://whosebug.com/users/6155520/b-b) 的 Stack Overflow 答案。

我会创建一个自定义 class 单元格,并在 class 中进行 UITextField 初始化(为其指定一个变量名)。

class TextFieldCell: UITableViewCell {
    let textField = // initialize text field

    // don't forget to add its constraints and init functions
}

然后在您的 VC9done 函数中,您可以调用 table 视图的 cellForRow 函数并获取包含所需 TextField 的单元格。获得此单元格后,您可以将其转换为自定义 class,然后访问其 .textField 字段及其包含的任何文本。

你可以试试这个

class VC12: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

@IBOutlet weak var VC12TableView: UITableView!

var VC12Inputs = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.VC12TableView.dataSource = self

    VC12Inputs.append("Input 1")
    VC12Inputs.append("Input 2")
    VC12Inputs.append("Input 3")
}

func textFieldDidEndEditing(_ textField: UITextField) {
    VC12Inputs[textField.tag] = textField.text! //to update arr with latest value 
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = VC12TableView.dequeueReusableCell(withIdentifier: "cell") ?? makeCell()
    let textField = cell.viewWithTag(1) as! UITextField
    let row = indexPath.row
    textField.tag = row      //**set tag value here** 
    textField.delegate = self   //**set delegate**

    textField.placeholder = VC12Inputs[row]

    return cell
}

func makeCell() -> UITableViewCell {
    let textField = UITextField(frame: CGRect.zero)

    textField.tag = 1 //don't set tag value here or set with indexpath.item
    . .....
    .....

}

@IBAction func VC9Done(_ sender: Any)
{
    print(VC12Inputs) //here you'll get all updated value at any time 
}

借助UITextFieldDelegate方法,我们可以实现。

var textFieldTextDict = [Int : String]()

func textFieldDidEndEditing(_ textField: UITextField) {

    let cellPosition = textField.superview?.convert(CGPoint.zero, to: yourTableView)
    let indPath = yourTableView.indexPathForRow(at: cellPosition!)

    if textField.text != ""
    {
        textFieldTextDict[(indPath?.row)!] = textField.text
    }      

}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true
}

@IBAction func VC9Done(_ sender: Any)
{
    self.view.endEditing(true) // ONE LINE

    print("addedValues   ", textFieldTextDict)
}

@IBAction func formSubmitAcn(_ sender: Any)
{
    // as per three textfields

    if textFieldTextDict.count == 3
    {
        print("success")
    }
    else 
    {
        print("failure")
    }
}

OutPut

addedValues   [0: "name ", 2: "age", 3: "address", 1: "email", 4: "phone"]