Swift开发:如何在另一个ViewController中向数组追加元素?
问题原因
你当前代码里的planExercise()是新建了一个planExerciseViewController的实例,而非操作界面上正在显示的那个原实例。你修改的是新实例的exerciseList数组,原VC的自然不会有任何变化。
解决方案
以下是几种常用的解决方式:
方式1:闭包传递数据
在TableViewDetail中定义闭包,点击按钮时触发闭包把选中的Exercise回传给原VC。
- 修改
TableViewDetail代码:
class TableViewDetail: UIViewController { // 定义闭包,用于传递选中的Exercise var addExerciseHandler: ((Exercise) -> Void)? var selectedExercise: Exercise! @IBAction func didTapAdd(){ // 调用闭包传递数据 addExerciseHandler?(selectedExercise) // 根据跳转方式关闭页面,present用下面这句,push则用navigationController?.popViewController(animated: true) dismiss(animated: true) } }
- 在
planExercise跳转时绑定闭包:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let detailVC = segue.destination as? TableViewDetail else { return } // 传递选中的Exercise(按需补充你的选中逻辑) detailVC.selectedExercise = ... // 绑定闭包,处理添加逻辑 detailVC.addExerciseHandler = { [weak self] newExercise in self?.exerciseList.append(newExercise) // 刷新TableView(如果有列表展示的话) self?.tableView.reloadData() } }
方式2:代理模式
通过自定义代理协议实现数据反向传递。
- 定义代理协议:
protocol TableViewDetailDelegate: AnyObject { func didAddExercise(_ exercise: Exercise) }
- 修改
TableViewDetail代码:
class TableViewDetail: UIViewController { weak var delegate: TableViewDetailDelegate? var selectedExercise: Exercise! @IBAction func didTapAdd(){ delegate?.didAddExercise(selectedExercise) dismiss(animated: true) } }
- 让
planExercise遵守协议并实现方法:
class planExercise: UIViewController, TableViewDetailDelegate { // 原有代码... override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let detailVC = segue.destination as? TableViewDetail else { return } detailVC.selectedExercise = ... detailVC.delegate = self } // 实现代理方法 func didAddExercise(_ exercise: Exercise) { exerciseList.append(exercise) tableView.reloadData() } }
方式3:共享数据模型(复杂场景适用)
如果多个页面都需要访问或修改Exercise列表,可以用单例模型统一管理数据。
- 创建单例数据管理类:
class ExerciseManager { static let shared = ExerciseManager() var exerciseList = [ Exercise(type: "Cardiovascular", name: "Walking", imageName: "walking", calories: 150, time: 30, isComplete: false), Exercise(type:"Strength",name:"Chair Squats",imageName:"cycling", calories: 200, time: 15, isComplete: false), Exercise(type: "Flexibility", name: "Seated Toe Touch", imageName: "squats", calories: 100, time: 15, isComplete: false) ] private init() {} // 私有初始化,防止创建多个实例 }
- 在两个VC中使用共享模型:
// planExercise中 class planExercise: UIViewController { // 直接使用共享模型的数组 var exerciseList: [Exercise] { ExerciseManager.shared.exerciseList } // 刷新列表时直接基于这个数组更新 } // TableViewDetail中 @IBAction func didTapAdd(){ ExerciseManager.shared.exerciseList.append(selectedExercise) dismiss(animated: true) // 若需通知planExercise刷新,可搭配NotificationCenter发送通知或添加监听闭包 }
内容的提问来源于stack exchange,提问作者Kashyap Hegde Kota
相关产品推荐
相关产品推荐

