swift 中视图控制器之间的委托
Delegates between viewcontrollers in swift
我正在尝试在我的应用程序中实现两个视图控制器之间的委托,以便在其中一个视图控制器中重新加载 tableView 数据,但是当我按下按钮时没有任何反应,我已经用断点对其进行了测试,我是不是忘记了我的实现中有什么?
发送ViewController
protocol UpdateDelegate {
func updateExerciseCells()
}
class ExerciseVC: UIViewController {
var delegate:UpdateDelegate?
@IBAction func saveWorkoutPressed(_ sender: Any) {
exercise = Exercise(name: exerciseNameInput.text!, weight: weightInput.text!, reps: repsInput.text!, sets: setsInput.text!, difficulty: "")
WorkoutService.instance.exercises.append(exercise!)
self.delegate?.updateExerciseCells()
dismiss(animated: true, completion: nil)
}
}
正在接收ViewController
class WorkoutVC: UIViewController, UpdateDelegate {
var alert:ExerciseVC = ExerciseVC()
override func viewDidLoad() {
super.viewDidLoad()
alert.delegate = self
}
func updateExerciseCells() {
//update table
}
}
根据您的代码,您在 class ExerciseVC 中使用了 IBAction 方法,这意味着您在 Storyboard 中有这个控制器。但是你初始化 ExerciseVC 就像
var alert:ExerciseVC = ExerciseVC()
这是不正确的,因为在这种情况下永远不会调用 IBAction 方法。尝试使用
let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "yourViewControllerID")
这里发生的事情是您正在以编程方式创建 ExerciseVC
,但是您的 Main.storyboard
正在通过 segue 创建另一个。所以 delegate
在 segue 创建的那个上是 nil。
将此功能添加到您的 WorkoutVC
:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ExerciseVC {
vc.delegate = self
}
}
您可以删除 WorkoutVC
中的 alert
变量,任何对它的引用都已被 UIStoryBoard
实例化
我正在尝试在我的应用程序中实现两个视图控制器之间的委托,以便在其中一个视图控制器中重新加载 tableView 数据,但是当我按下按钮时没有任何反应,我已经用断点对其进行了测试,我是不是忘记了我的实现中有什么?
发送ViewController
protocol UpdateDelegate {
func updateExerciseCells()
}
class ExerciseVC: UIViewController {
var delegate:UpdateDelegate?
@IBAction func saveWorkoutPressed(_ sender: Any) {
exercise = Exercise(name: exerciseNameInput.text!, weight: weightInput.text!, reps: repsInput.text!, sets: setsInput.text!, difficulty: "")
WorkoutService.instance.exercises.append(exercise!)
self.delegate?.updateExerciseCells()
dismiss(animated: true, completion: nil)
}
}
正在接收ViewController
class WorkoutVC: UIViewController, UpdateDelegate {
var alert:ExerciseVC = ExerciseVC()
override func viewDidLoad() {
super.viewDidLoad()
alert.delegate = self
}
func updateExerciseCells() {
//update table
}
}
根据您的代码,您在 class ExerciseVC 中使用了 IBAction 方法,这意味着您在 Storyboard 中有这个控制器。但是你初始化 ExerciseVC 就像
var alert:ExerciseVC = ExerciseVC()
这是不正确的,因为在这种情况下永远不会调用 IBAction 方法。尝试使用
let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "yourViewControllerID")
这里发生的事情是您正在以编程方式创建 ExerciseVC
,但是您的 Main.storyboard
正在通过 segue 创建另一个。所以 delegate
在 segue 创建的那个上是 nil。
将此功能添加到您的 WorkoutVC
:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ExerciseVC {
vc.delegate = self
}
}
您可以删除 WorkoutVC
中的 alert
变量,任何对它的引用都已被 UIStoryBoard