You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中点击提交按钮获取TableView单元格TextField值时遇数组越界错误

解决TableView单元格TextField取值时数组越界问题

问题描述

在TableView的单元格中添加TextField后,尝试在编辑TextField时将值存入数组,执行textfieldDataArray[tag] = textField.text ?? ""时触发报错:

线程1:致命错误:索引超出范围

现有代码如下:

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初始化为空数组,但TableView有10行数据,当TextField触发编辑事件时,直接通过tag(0-9)作为索引给数组赋值,此时数组长度为0,访问超出数组范围的索引必然触发越界错误。此外,当前代码未处理TableView的cell复用问题,滚动后已输入的内容会丢失。

解决方案

1. 初始化数组至对应长度

在viewDidLoad中初始化数组,填充与TableView行数一致的空字符串,确保每个索引都有对应的元素:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    // 初始化数组,对应10行TableView的空值
    textfieldDataArray = Array(repeating: "", count: 10)
}

2. 处理Cell复用,恢复输入内容

在cellForRowAt方法中,将数组中保存的值回显到TextField,避免滚动时丢失已输入的内容:

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
    // 回显已保存的TextField值
    cell.textFieldData.text = textfieldDataArray[indexPath.row]
    
    cell.textFieldData.addTarget(self, action: #selector(textfieldDidChange(_:)), for: .editingChanged)
    
    cell.tableLbl.text = String(indexPath.row + 1)
    return cell
}

3. 完善提交按钮逻辑

提交时直接使用已保存所有值的textfieldDataArray即可:

@IBAction func submitButton(_ sender: UIButton) {
    let allTextFieldValues = textfieldDataArray
    print("所有TextField的值: \(allTextFieldValues)")
    // 后续业务逻辑使用该数组
}

效果验证

修改后,编辑TextField时不会再触发数组越界错误,滚动TableView也能保留已输入的内容,点击提交按钮可正确获取所有TextField的值。

内容的提问来源于stack exchange,提问作者Swift

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 12:30:29