UITableView分组内选中行索引获取及CoreData数据传递问题
解决UITableView分组行选中后传递FoodItem到详情页的问题
你的代码里有几个关键错误导致无法正确获取选中的FoodItem,我帮你梳理并修正:
问题分析
- 错误创建空FoodItem实例:你新建了一个空的
FoodItem(),这不仅没用,还会因为foodItem.type!是nil而触发崩溃(强制解包空值) - 错误计算选中行索引:你把
row设为allFoodItems[section].count,这是该分组的总行数,根本不是选中行的索引 - 类型不匹配的赋值:你把
IndexPath对象赋值给详情页的foodItem属性,而详情页需要的是FoodItem实例,类型完全不对
修正后的代码
直接利用系统传入的indexPath就能精准拿到选中的FoodItem,修改后的didSelectRowAt方法如下:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 直接通过indexPath的section和row获取分组内对应的FoodItem let selectedFoodItem = allFoodItems[indexPath.section][indexPath.row] // 初始化详情页并传递选中的FoodItem let foodItemDetailController = FoodItemDetailController() foodItemDetailController.foodItem = selectedFoodItem // 跳转到详情页 navigationController?.pushViewController(foodItemDetailController, animated: true) // 可选:选中后取消行的高亮状态,提升交互体验 tableView.deselectRow(at: indexPath, animated: true) }
关键说明
- 你的
allFoodItems是二维数组,indexPath.section对应分组的索引,indexPath.row对应该分组内的行位置,直接通过allFoodItems[indexPath.section][indexPath.row]就能拿到选中的FoodItem - 确保你的
FoodItemDetailController里有对应的属性接收数据,比如:class FoodItemDetailController: UIViewController { var foodItem: FoodItem! // 或者用可选类型var foodItem: FoodItem?,根据你的需求调整 // 后续可以用这个foodItem来展示详情 } - 额外检查:确认
allFoodItems的分组顺序和foodItemTypes的顺序完全一致,这样tableView的section对应的分组数据才是正确的
内容的提问来源于stack exchange,提问作者Andy Bernard
相关产品推荐
相关产品推荐

