我在表格视图单元格中添加了文本字段,并希望在提交按钮中添加所有文本字段值
代码:如何在
submitButton
中添加表格视图文本
class TableCell: UITableViewCell{
@IBOutlet weak var tableLbl: UILabel!
@IBOutlet weak var textFieldData: UITextField!
}
class TableviewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
var selectedRows = [Int]()
var textfieldDataArray = [String]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
cell.textFieldData.delegate = self
cell.textFieldData.tag = indexPath.row
cell.textFieldData.addTarget(self, action: #selector(textfieldDidChange(_:)), for: .editingChanged)
cell.tableLbl.text = String(indexPath.row + 1)
return cell
}
@objc func textfieldDidChange(_ textField: UITextField) {
let tag = textField.tag
textfieldDataArray[tag] = textField.text ?? ""
}
@IBAction func submitButton(_ sender: UIButton) {
var selectedTextfieldValues = [String]()
print("Selected Textfield Values: \(selectedTextfieldValues)")
// Use selectedTextfieldValues as needed
}
}
在
textfieldDataArray[tag] = textField.text ?? ""
出现错误
线程 1:致命错误:索引超出范围
我认为更好的方法是定义一个单元格数据来保存
String
值,它比分配 tag
并同时重用单元格更安全、更容易处理。
可能是:
struct TableCellData {
var text = ""
}
class TableCell: UITableViewCell {
...
var changedText: ((String) -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
textFieldData.addTarget(self, action: #selector(textfieldDidChange), for: .editingChanged)
}
func bind(_ data: TableCellData) {
textFieldData.text = data.text
}
@objc private func textfieldDidChange(_ textField: UITextField) {
changedText?(textField.text ?? "")
}
}
然后当这些单元出队时:
class TableviewViewController {
//How many cell you want
private var list: [TableCellData] = []
override func viewDidLoad() {
super.viewDidLoad()
list = Array(repeating: TableCellData(), count: 10)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.bind(list[indexPath.row])
cell.changedText = { [weak self] text in
guard let self = self else { return }
self.list[indexPath.row].text = text
}
return cell
}
private func getAllString() {
let strings = list.map { $0.text }
print(strings)
}
}