如何从 UITableViewCell 获取文本字段的值?

Posted

技术标签:

【中文标题】如何从 UITableViewCell 获取文本字段的值?【英文标题】:How To get values of textfields from a UITableViewCell? 【发布时间】:2016-12-19 10:00:56 【问题描述】:

所以我有这个UITableView 有 4 个UITextField 的单元格,我想在按钮单击时获取它们的值。

此代码不检索任何值。

@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)")

这是 TableView 的截图

【问题讨论】:

更多细节会很有用。 你打印输出吗?怎么了 ?请解释更多 把你的表格视图的截图放上去 好吧,当我把它们打印出来时,我什么也没得到,即使我在文本字段上输入了值。 一如既往,不要从视图(单元格)获取数据,从模型(数据源数组)获取数据。并且从不cellForRow...之外创建单元格 【参考方案1】:

我终于通过这个简单的解决方案想通了。

@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)")

【讨论】:

我忘了提到所有文本字段都在第一个表格单元格部分和行(行:0,部分:0)中,我还有其他部分,但视图不会显示除非我向下滚动。 多行怎么办?【参考方案2】:

好的。当您按下按钮时,您正在使 tableViewCell 出队。

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

我相信您希望像这样获得对现有 tableViewCell 的引用:

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

即使这样可行,我也不建议使用这种方法。如果用户使用像 iPhone 4 这样的小屏幕手机并且屏幕上看不到某些单元格怎么办?我认为在这种情况下,tableView.cellForRow 会为不可见的单元格返回nil

我建议在每个带有文本字段的单元格中实现textField:shouldChange,并代表tableView 的viewController。当单元格中的文本发生更改时,委托应将更改传播到视图控制器,视图控制器会将值保存在实例变量中。

然后,当您按下按钮时,您只需从实例变量中获取值。

【讨论】:

正确。这应该是原始方法【参考方案3】:

// 第一步

在 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
      

//第二步

在 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
    

当键盘消失时,您可以在valueToPass 中找到TextField 值

【讨论】:

【参考方案4】:

我想你的 tableViewCells 不是动态的。 您的单元格方法将如下所示。

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

在你的 UITableView 处理类(符合 UITextFieldDelegate 协议)中,写这个。

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;

然后你就可以提交了。

【讨论】:

Swift 中不需要break switch,因为它不是失败的,与许多语言相反。 @EricAya ,我不是来自 Swift 并且在 case 之后添加 break 并没有什么坏处。这仍然是一个很好的编程习惯。如果你在没有可执行语句的情况下离开大小写或默认值,Swift 仍然会抱怨。【参考方案5】:
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;

【讨论】:

【参考方案6】:

在我看来,您应该在 tableCell 类中实现 TextField 委托方法,并在 tableCell 类中管理所有验证和输入文本。

现在,您将需要获取所有输入的值,为此,您必须使用 tableCell 类中的协议并使用委托将输入的值发送到 viewController 还带有标签以识别输入的值,例如电话号码或电子邮件。

使用这种方式,您的代码将被精简和结构化。

编码愉快!!

【讨论】:

以上是关于如何从 UITableViewCell 获取文本字段的值?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 cellForRowAtIndexPath 从 TableView 中获取自定义 UITableViewCell?

如何从 UITableViewCell 中获取价值

如何从自定义 UITableViewCell 获取值到 ViewController?

如何从 UIButton 操作方法获取 UITableViewCell 对象?

如何从 UITableViewCell 获取当前位置(帧)?

如何从 cgpoint 获取 UItableviewcell?