【发布时间】:2019-01-07 21:07:37
【问题描述】:
我正在快速工作。我有一个位于表格视图单元格中的文本字段。我正在尝试将每个文本字段的文本存储在 tableview 中,以便当用户添加或删除一行,然后 tableview 重新加载数据时,文本字段会填充适当的数据。
我尝试添加一个 textfielddidendeditting 函数,但由于某种原因它没有被调用。
编辑:
这是我的代码:
tableViewController:
import UIKit
var rowCount = 0
var textArray = [String]()
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowCount
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
return cell
}
@IBAction func addRow(_ sender: Any) {
rowCount = rowCount + 1
textArray.append("")
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
rowCount = rowCount - 1
textArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
}
}
}
tableViewCell:
import UIKit
class TableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if let myIndexPath = tableView.indexPathForSelectedRow {
let newText = textField.text
textArray.insert(newText, at: myIndexPath)
}
return true
}
}
【问题讨论】:
-
"我尝试添加一个 textfielddidendeditting 函数,但由于某种原因它没有被调用" 但是除非您向我们展示您的代码,否则我们无法告诉您原因是什么。
-
另外,这是一个非常常见的需求(将表格视图单元格中的文本字段中的文本传递到表格视图的模型数据中)。问之前有没有试过搜索?