Swift中视图控制器之间的委托

3

我正在尝试在我的应用程序中实现委托,以便在两个视图控制器之间重新加载其中一个tableView的数据,但当我按下按钮时,什么也没有发生,我已经使用断点测试过了,我的实现是否有遗漏?

发送视图控制器

     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)

            }
}

接收视图控制器

class WorkoutVC: UIViewController, UpdateDelegate {

    var alert:ExerciseVC = ExerciseVC()




    override func viewDidLoad() {
        super.viewDidLoad()
        alert.delegate = self
    }

 func updateExerciseCells() {
        //update table
    }

}

我已经在两个地方设置了断点,断点命中了IBAction函数,但没有命中updateExerciseCells() - ShedSports
在exerciseVC的viewDidLoad中,它是nil。 - ShedSports
IBAction saveWorkoutPressed(sender:) 块内部是 nil 吗? - elight
在这种情况下,self.delegate?.updateExerciseCells() 将不会被调用。这是你的问题。确保 self.delegate? 不为 nil,并且它将调用 saveWorkouPressed()。如果您能够通过 Github 共享项目,我可以看一下。今天休息 :) - elight
你认为这可能是因为ExerciseVC是页面Sheet而不是完整的页面VC吗? - ShedSports
显示剩余5条评论
2个回答

3
在这里发生的是您通过编程方式创建了ExerciseVC,但是您的Main.storyboard通过segue创建了另一个ExerciseVC。因此,由segue创建的那个ExerciseVCdelegate为nil。
将以下函数添加到您的WorkoutVC中:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ExerciseVC {
        vc.delegate = self
    }
}

您可以删除WorkoutVC中的alert变量和任何对它的引用,因为您将使用的一个已经由UIStoryBoard实例化了。


0

根据您的代码,您在ExerciseVC类中使用了IBAction方法,这意味着您在Storyboard中拥有此控制器。但是您初始化ExerciseVC的方式如下:

var alert:ExerciseVC = ExerciseVC()

这是不正确的,因为在这种情况下,IBAction方法永远不会被调用。请尝试使用

let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "yourViewControllerID")

当按钮被按下时,IBAction会被调用。 - ShedSports

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接