Delegates in swift?

前端 未结 12 1324
天命终不由人
天命终不由人 2020-11-22 03:27

How does one go about making a delegate, i.e. NSUserNotificationCenterDelegate in swift?

12条回答
  •  甜味超标
    2020-11-22 04:22

    Very easy step by step (100% working and tested)

    step1: Create method on first view controller

     func updateProcessStatus(isCompleted : Bool){
        if isCompleted{
            self.labelStatus.text = "Process is completed"
        }else{
            self.labelStatus.text = "Process is in progress"
        }
    }
    

    step2: Set delegate while push to second view controller

    @IBAction func buttonAction(_ sender: Any) {
    
        let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
        secondViewController.delegate = self
        self.navigationController?.pushViewController(secondViewController, animated: true)
    }
    

    step3: set delegate like

    class ViewController: UIViewController,ProcessStatusDelegate {

    step4: Create protocol

    protocol ProcessStatusDelegate:NSObjectProtocol{
    func updateProcessStatus(isCompleted : Bool)
    }
    

    step5: take a variable

    var delegate:ProcessStatusDelegate?
    

    step6: While go back to previous view controller call delegate method so first view controller notify with data

    @IBAction func buttonActionBack(_ sender: Any) {
        delegate?.updateProcessStatus(isCompleted: true)
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func buttonProgress(_ sender: Any) {
        delegate?.updateProcessStatus(isCompleted: false)
        self.navigationController?.popViewController(animated: true)
    
    }
    

提交回复
热议问题