使用委托从模态视图控制器中调用另一个视图控制器中的方法

时间:2018-08-12 14:21:05

标签: ios swift delegates protocols swift4

我正在使用模式搜索来创建要关闭的视图控制器,然后在原始视图控制器中调用方法。我使用了协议/代理模式,但由于某种原因,从未调用过该方法。代码如下:请注意,我删除了许多不相关的代码以保持此处干净

谢谢!

VC1:

final class WorkoutViewController: UIViewController, StartWorkoutButtonDelegate {

weak var dataSource: WorkoutViewControllerDataSource!
private var workout: Workout!
private var workoutDataViewController: WorkoutDataViewController?
private var workoutFinishViewController: WorkoutFinishViewController?
private let workoutFinishViewControllerSegueIdentifier = "Workout Finish View Controller Segue"

@IBOutlet private var primaryActionButton: UIButton!
@IBOutlet private var pageControl: UIPageControl!

// MARK: - Handling View Lifecycle

override func viewDidLoad() {
    super .viewDidLoad()
    let workoutType = dataSource.workoutType(for: self)
    workout = Workout(workoutType: workoutType, managedObjectContext: persistentContainer.viewContext)
    setPrimaryActionButtonLabel()
}

// MARK: - Handling Storyboard Segues

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    if let destinationWorkoutFinishViewController = segue.destination as? WorkoutFinishViewController {
        workoutFinishViewController = destinationWorkoutFinishViewController
    }
}

// MARK: - Managing Start and Pause 

@IBAction func startOrPauseWorkout() {
    if workout.isPaused {
        startWorkout()
    } else {
        pauseWorkout()
    }
}

}

VC 2:

protocol StartWorkoutButtonDelegate: AnyObject {
func startOrPauseWorkout()
 }

class WorkoutFinishViewController: UIViewController {

weak var delegate: StartWorkoutButtonDelegate?

@IBAction func startWorkout() {
    self.delegate?.startOrPauseWorkout()
    self.dismiss(animated: true, completion: nil)
}

@IBAction func finishWorkout() {
}

override func viewDidLoad() {
    super.viewDidLoad()

}
}

1 个答案:

答案 0 :(得分:1)

在这里设置代表

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   super.prepare(for: segue, sender: sender)
   if let destinationWorkoutFinishViewController = segue.destination as? WorkoutFinishViewController {
     destinationWorkoutFinishViewController.delegate = self
   }
}