我有一个 UITableView,我的原型单元由一个标签和一个 TextField 组成。我还有一个 MyClass 类,它包含函数 func1、func2、fun3、... 我有几个 ViewControllers 使用相同的 tableViewCell 原型。每个 viewController 都会有一个 MyClass 的实例,分别称为 inst1、inst2 和 inst3。当我在 FirstViewController 的 TableView 中输入文本时,我希望每一行都从对应于该行的 MyClass 实例调用一个函数。
因此,当我在 FirstViewController 的第 1 行中输入文本时,我想将输入到 textField 中的数据传递到 inst1 的 func1 中。当数据输入到 FirstViewController 的第 2 行时,我希望将文本字段中的数据传递到 inst1 的 func2 中。依此类推。
我对此很陌生,非常感谢一些帮助弄清楚如何做到这一点。让我知道这是否没有意义,我可以尝试改写它。我真的需要帮助。提前致谢!
*更新问题以显示我的代码
下面是我的代码:FirstViewController.swift
extension FirstViewController: MyCellDelegate {
func MyCell(_ cell: UITableViewCell, didEnterText text: String) {
if let indexPath = tableView.indexPath(for: cell) {
if (indexPath.hashValue == 0) {
inst1.func1(one: text)
}
if (indexPath.hashValue == 1) {
inst1.func2(two: text)
}
}
totalText.text = inst1.getMyTotal()
}
}
import UIKit
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let inst1 = MyClass()
@IBOutlet weak var totalText: UILabel!
@IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 11
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myTableCell") as! TableViewCell
let text = cell.cellData[indexPath.row]
cell.myTextField.tag = indexPath.row
cell.delegate = self
cell.myLabel.text = text
cell.myTextField.placeholder = text
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
TableViewCell.swift
import UIKit
protocol MyCellDelegate: class {
func MyCell(_ cell: UITableViewCell, didEnterText text: String)
}
class TableViewCell: UITableViewCell {
weak var delegate: MyCellDelegate?
public var cellData: [String] = ["1","2","3","4","5","6","7","8","9","10","11"]
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myTextField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
}
}
当我在 FirstViewController 扩展中设置断点时,它永远不会运行该代码。