Get indexPath of UITextField in UITableViewCell with Swift

前端 未结 4 1146
庸人自扰
庸人自扰 2021-02-04 08:26

So, I\'m building a Detail View Controller App that presents a Table with a two-part cell: the label and the Text Field.

I\'m trying to retrieve the Text Field value and

4条回答
  •  粉色の甜心
    2021-02-04 09:25

    Using superview and typecasting isn't a preferred aaproach. The best practice is to use delegate pattern. If you have a textField in DemoTableViewCell which you are using in DemoTableViewController make a protocol DemoTableViewCellDelegate and assign delegate of DemoTableViewCell to DemoTableViewController so that viewcontroller is notified when eiditing ends in textfield.

    protocol DemoTableViewCellDelegate: class {
      func didEndEditing(onCell cell: DemoTableViewCell)
    }
    
    class DemoTableViewCell: UITableViewCell {
      @IBOutlet var textField: UITextField!
    
      weak var delegate: DemoTableViewCellDelegate?
    
      override func awakeFromNib() {
        super.awakeFromNib()
        textField.delegate = self
      }
    }
    
    extension DemoTableViewCell: UITextFieldDelegate {
      func textFieldDidEndEditing(_ textField: UITextField) {
        delegate.didEndEditing(onCell: self)
      }
    }
    
    class DemoTableViewController: UITableViewController {
    
      override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
        let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: DemoTableViewCell.self, for: indexPath)
        cell.delegate = self
        return cell
      }
    
    }
    
    extension DemoTableViewController: DemoTableViewCellDelegate {
      func didEndEditing(onCell cell: DemoTableViewCell) {
        //Indexpath for the cell in which editing have ended.
        //Now do whatever you want to do with the text and indexpath.
        let indexPath = tableView.indexPath(for: cell)
        let text = cell.textField.text
      }
    }
    

提交回复
热议问题