iOS开发:如何将数组元素逐个加载到UITableViewCell单独行
解决方案
问题根源分析
GetMoves()里每次循环都调用reloadData(),会导致表格频繁刷新,且未清空旧数据,重复点击按钮会让数组元素重复累加。- 你之前在
cellForRowAt里加while循环是错误的——UITableView的cellForRowAt方法本身就是系统为每一行单独调用一次,indexPath.row就是当前行对应的数组下标,不需要自行循环遍历数组。错误的循环写法要么让每个单元格加载所有元素,要么因逻辑问题导致未返回cell触发报错。
修正后的代码
override func viewDidLoad() { super.viewDidLoad() Table.dataSource = self } @IBAction func Buttonpressed() { GetMoves() } func GetMoves() { // 清空旧数据,避免重复点击时元素累加 ChosenMoves.removeAll() // 安全解包输入框内容,处理无效输入(非数字、超出数组范围等) guard let inputText = Field.text, let chosenNumber = Int(inputText), chosenNumber > 0, chosenNumber <= Moves.count else { return } // 循环添加指定数量的元素 for i in 0..<chosenNumber { ChosenMoves.append(Moves[i]) } // 所有元素添加完成后统一刷新表格 Table.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 表格行数等于数组元素个数 return ChosenMoves.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 复用单元格 let cell = Table.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell // 用当前行下标取对应数组元素,赋值给单元格标签 let moveString = ChosenMoves[indexPath.row] cell.CellLabel.text = moveString return cell }
关键修改说明
GetMoves函数:
- 新增
removeAll()清空旧数据,避免重复点击时数据残留 - 用
guard做安全解包,防止输入无效内容导致崩溃 - 把
reloadData()移到循环结束后,减少不必要的表格刷新 - 改用
for-in循环,比while更简洁安全
- 新增
cellForRowAt函数:
- 移除多余的循环和变量,直接通过
indexPath.row获取当前行对应的数组元素,确保每个单元格只显示一个数组元素,对应表格的一行
- 移除多余的循环和变量,直接通过
修改后点击按钮,就能让指定数量的名字逐个显示在UITableView的单独一行中。
内容的提问来源于stack exchange,提问作者CmediaIOSDev
相关产品推荐
相关产品推荐

