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

Swift如何将表格选中元素的数组索引赋值给变量?

获取UITableView选中元素的数组索引并赋值给变量

如果要获取UITableView选中行对应的数据源数组索引,直接用indexPath.row即可,它和数据源数组firstList的索引是一一对应的。

你原来的代码里,firstList[indexPath.row]取的是数组中对应位置的元素,而非索引本身。修正后的代码如下:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    // 赋值选中元素的数组索引到变量
    let selectedIndex = indexPath.row
    print("选中元素的数组索引:\(selectedIndex)")
    
    // 若需要同时获取选中的元素,可保留这行
    let selectedElement = firstList[indexPath.row]
    print("选中的元素:\(selectedElement)")
    
    let kategorilerVC = KategoriController()
    // 可将索引传递给下一个控制器,示例:
    // kategorilerVC.selectedIndex = selectedIndex
    // self.present(kategorilerVC, animated: true)
}
  • selectedIndex就是你要的数组索引变量,直接通过indexPath.row赋值即可。
  • 注意区分数组索引(indexPath.row)和数组元素(firstList[indexPath.row])的区别,避免混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:35:55