Swift iOS中TableViewCell获取数组值时索引越界问题求助
搞定TableView "Index out of range" 错误
嘿,我一眼就看出问题出在哪了!你设置numberOfRowsInSection返回wInstockArray.count + 1,但在cellForRowAt里直接用indexPath.row去取数组元素,这可不就越界了嘛!
问题到底出在哪?
举个例子:如果你的wInstockArray有3个元素,那count就是3,numberOfRowsInSection会返回4行(对应索引0、1、2、3)。但数组里只有索引0、1、2的元素,当indexPath.row等于3的时候,你去访问wInstockArray[3],肯定会触发"Index out of range"错误啊!
两种解决方案任你选
方案1:区分普通行和额外行(适合你需要多一行的场景)
在cellForRowAt里判断当前行是不是额外的那一行,是的话就单独处理,别去碰数组:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "你的CellID", for: indexPath) // 只有当前行在数组范围内时,才去取数组的值 if indexPath.row < wInstockArray.count { let item = wInstockArray[indexPath.row] cell.textLabel?.text = item } else { // 这里处理额外行的内容,比如显示"添加新项" cell.textLabel?.text = "点击添加新内容" } return cell }
方案2:去掉多余的一行(如果多一行是误操作)
要是你根本不需要多那一行,直接把numberOfRowsInSection改成返回数组长度就行:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return wInstockArray.count }
额外提醒
- 每次修改
wInstockArray之后,一定要调用tableView.reloadData()刷新表格,不然表格的行数和数组内容会不同步,还可能出其他问题 - 如果是动态添加元素,推荐用
tableView.insertRows(at: [IndexPath(row: wInstockArray.count, section: 0)], with: .automatic)来更新,比直接reload更流畅,也能避免同步问题
内容的提问来源于stack exchange,提问作者iOS Developer
相关产品推荐
相关产品推荐

