iOS Swift开发中ViewController跳转后completion回调不执行如何修复
问题原因
你在editTimerButtinPresed方法中手动创建的EditTimerViewController实例,和performSegue触发跳转时系统创建的EditTimerViewController实例是完全独立的两个对象。你给手动创建的临时实例设置的completion回调,根本没有赋值给实际展示在界面上的控制器,所以点击保存时回调自然不会执行。
修复步骤
- 删除
editTimerButtinPresed方法中多余的实例创建和回调赋值代码,只保留触发segue的逻辑:
@IBAction func editTimerButtinPresed(_ sender: UIButton) { self.performSegue(withIdentifier: "goToEditTimer", sender: self) }
- 在
prepare(for:sender:)方法中给实际跳转的控制器设置completion回调,同时补充定时器参数重置逻辑,避免回调触发后定时器还是用旧的时长运行:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToEditTimer" { let destinationVC = segue.destination as! EditTimerViewController destinationVC.duration = Int(totalTime) // 给实际跳转的控制器绑定回调 destinationVC.completion = { [weak self] duration in DispatchQueue.main.async { guard let self = self, let duration = duration else { return } self.totalTime = Double(duration) // 重置定时器相关参数,新时长才会生效 self.secondsRemaining = self.totalTime self.secondsPassed = 0 self.timerLabel.text = "\(duration)s" self.progressBar.progress = 0 // 如果当前定时器在运行,可以在这里加代码停止旧定时器 print("editTimer completed, totalTime now is \(self.totalTime)") } } print("Pasing duration = \(totalTime) to Edit screen") } }
修改完成后触发编辑流程,点击保存就能看到预期的打印输出,定时器时长也会同步更新。
内容的提问来源于stack exchange,提问作者Kosh
相关产品推荐
相关产品推荐

