How To get values of textfields from a UITableViewCell?

ⅰ亾dé卋堺 提交于 2019-12-21 05:38:11

问题


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 values.

@IBAction func printBtnAction(_ sender: Any) {

    let cell = self.myTableView.dequeueReusableCell(withIdentifier: "manualAddC1") as! AddFriendC1Cell

    let alias = cell.aliasTextField.text!
    let primaryPhone = cell.primaryPhoneTextField.text!
    let secondaryPhone = cell.seondaryPhoneTextField.text!
    let email = cell.emailAddressTextField.text!

    print("Alias: \(alias), Phone: \(primaryPhone), Phone2: \(secondaryPhone), Email: \(email)")
}

This is the screenshot of the TableView


回答1:


I finally figured it out with this simple solution.

@IBAction func saveBtnAction(_ sender: Any) {

    let index = IndexPath(row: 0, section: 0)
    let cell: AddFriendC1Cell = self.myTableView.cellForRow(at: index) as! AddFriendC1Cell
    self.alias = cell.aliasTextField.text!
    self.primaryPhone = cell.primaryPhoneTextField.text!
    self.secondaryPhone = cell.seondaryPhoneTextField.text!
    self.email = cell.emailAddressTextField.text!

    print("Alias: \(self.alias), Phone: \(self.primaryPhone), Phone2: \(self.secondaryPhone), Email: \(self.email)")
}



回答2:


OK. You are dequeueing a tableViewCell when you press on a button.

let cell = self.myTableView.dequeueReusableCell(withIdentifier: "manualAddC1") as! AddFriendC1Cell

I believe that you want to get a reference to an existing tableViewCell like this:

   if let cell = tableView.cellForRow(at: indexPath) as? AddFriendC1Cell {
        // do what you need with cell
    }

Even though this would work, I wouldn't suggest this approach. What if user is using a smaller-screen phone like iPhone 4 and some cells are not visible on the screen? I think that in that case tableView.cellForRow would return nil for non-visible cell.

I would suggest implementing textField:shouldChange in each cell with text field with a delegate to the tableView's viewController. When text is changed in the cell, delegate should propagate the change to the viewController which would save the value in an instance variable.

Then, when you press on the button, you would simply take values from instance variables.




回答3:


I suppose your tableViewCells are not dynamic. Your cell method will looks like this.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellID") as! YourClass
    cell.yourTextField.tag = indexPath.row
//
// Alias will be tag 0
// Primary Phone will be tag 1
// Secondary Phone will be tag 2 
// Email Address will be tag 3, so on and so forth
// Then, attach to each delegate
//
    cell.yourTextField.delegate = self
}

Inside your UITableView handling class (which conforms to UITextFieldDelegate protocol), write this.

func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {
let kActualText = (textField.text ?? "") + string
switch textField.tag
{
case 0:
    aliasValueHolder = kActualText;
case 1:
    primaryPhoneValueHolder = kActualText;
case 2:
    secondaryPhoneValueHolder = kActualText;
case 3:
    emailAddressValueHolder = kActualText;
default:
    print("It is nothing");
}
return true;
}

Then you can submit it.




回答4:


In my opinion, you should implement TextField delegates methods in the tableCell class and manage all the validations and input text in tableCell class.

Now, you will need to fetch all entered values, for this, you have to use Protocol in tableCell class and send entered value using the delegate to viewController also with the tag to identify that which value has entered like the Phone number or email.

Using this way, your code will be reduced and structured.

Happy Coding !!




回答5:


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




回答6:


func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool {
    //        let kActualText = (textField.text ?? "") + string

    var kActualText = (textField.text! as NSString).replacingCharacters(in: range, with: string)

    kActualText = kActualText.trimmingCharacters(in: .whitespaces)

    if textField.tag == 0
    {
        email_address = kActualText;
    }
    else if textField.tag == 3
    {
        password = kActualText;
    }
    else
    {
        print("It is nothing")
    }

    return true;
}


来源:https://stackoverflow.com/questions/41219992/how-to-get-values-of-textfields-from-a-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!