How To get values of textfields from a UITableViewCell?

后端 未结 6 1673
天命终不由人
天命终不由人 2021-01-01 02:13

So I have thisUITableView cell that has 4 UITextField, and I want to get their values on button click.

This code does not retrieve any valu

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 02:35

    // 1st step

    In UITableViewCell

    import UIKit
    
    @objc protocol TableViewDelegate: NSObjectProtocol{
    
        func afterClickingReturnInTextField(cell: ThirdTableCell)
    }
    
    class TableViewCell: UITableViewCell, UITextFieldDelegate {
    
        @IBOutlet weak var enterTextField: UITextField!
        weak var tableViewDelegate: TableViewDelegate?
    
    
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
            enterTextField.delegate = self   
        }
    
        // @IBAction Of UITextfiled 
        @IBAction func tapHerre(_ sender: UITextField) {
    
            tableViewDelegate?.responds(to: #selector(TableViewDelegate.afterClickingReturnInTextField(cell:)))
            tableViewDelegate?.afterClickingReturnInTextField(cell: self)
        }
    
        // UITextField Defaults delegates
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    
            enterTextField.resignFirstResponder()
            return true
        }
        func textFieldDidEndEditing(_ textField: UITextField) {
    
            enterTextField = textField
        }  
    }
    

    // 2nd step

    In UITableViewCell

    extension ViewController: UITableViewDelegate, UITableViewDataSource, TableViewDelegate {
    
        var valueToPass : String?
    
        func afterClickingReturnInTextField(cell: ThirdTableCell) {
    
            valueToPass = cell.enterTextField.text
        }
    
        func numberOfSections(in tableView: UITableView) -> Int {
    
            return 1
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
            return youArray.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableview.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
            cell.enterTextField.text = youArray[indexPath.row]
            cell.tableViewDelegate = (self as TableViewDelegate)
            return cell
        }
    }
    

    When the keyboard disappears you can find TextField value in valueToPass

提交回复
热议问题