如何从 Custom UITableViewCell 获取值到 ViewController?

How do I get the values from Custom UITableViewCell to ViewController?

我在 UITableViewCell 上有两个 UITextField,它们的 IBOutlets 在名为 "CustomCell.swift" 的自定义 UITableViewCell class 中连接。 Enter 按钮位于 ViewController 的 UIView 上,其 IBAction 位于 UIViewController class 中,称为 "ViewController"。

单击 Enter 按钮后,我想查看两个文本字段是否为空。我该怎么做?请帮助

在您的 class 按钮操作所在的位置创建一个 Bool 变量

var isTextFieldTextEmpty: Bool!

然后在您的 table 查看数据源方法 cellForRowAtIndexPath 添加

if myCell.myTextField.text?.isEmpty == true {
        self.isTextFieldTextEmpty = true
    } else {
        self.isTextFieldTextEmpty = false
    }

然后在您的(输入)按钮的 IBAction 中添加

self.myTableView.reloadData()
self.myTableView.layoutIfNeeded()
print(self.isTextFieldTextEmpty) 

如果 table 视图的所有单元格中的所有文本字段都有文本,则打印 false,否则如果所有文本字段中只有一个文本字段没有文本,则打印 true

这是一个简单的解决方案。它适用于任意数量的单元格。

您需要做的是遍历单元格并确定特定单元格包含的 textField 是否为空。现在的问题是您将如何遍历单元格,是否有任何委托?答案是否定的

您必须手动构造 indexPaths 才能从 Table 中获取单元格。

这是一个简单的演练。你的设置非常正确。您的 ViewController 中应该有一个表格视图。所以,tableview 的 IBOutlet 应该在那里。我将我的 TableView 命名为 "myTableView"。 textField 的 Outlet 应该在 TableViewCell 里面,这也是对的。最后,Enter 按钮的操作方法应该在视图控制器中。

确保正确连接所有插座。

这是示例自定义 TableViewCell -

import UIKit

class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var internalTextField : UITextField!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

}

现在只需转到 ViewController.swift-

import UIKit

class ViewController: UIViewController, UITableViewDataSource  {

    @IBOutlet weak var myTableView : UITableView!

    var numberOfCells = 2  //you can update it to be any number

    override func viewDidLoad() {
        super.viewDidLoad()
        self.myTableView.dataSource! = self  //assign the delegate
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return numberOfCells
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell : CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomTableViewCell
        return cell;
    }

    @IBAction func pressedEnter(){

        var row  = 0

        while row < numberOfCells { //iterate through the tableview's cells

            let indexPath : NSIndexPath = NSIndexPath(forRow: row, inSection: 0) //Create the indexpath to get the cell
            let cell : CustomTableViewCell = self.myTableView.cellForRowAtIndexPath(indexPath) as! CustomTableViewCell

            if cell.internalTextField.text!.isEmpty{
                print("TextField is Cell \(row) is Empty")
            }
            else{
                print("TextField is Cell \(row) is NOT Empty")
            }
            row += 1
        }
    }
}

有评论说明一切。希望这有帮助。