我在第一个视图控制器ViewController中有一个标签,而在第二个vc中每个日期都有一个函数。我想在第二秒计时器启动后首先更新标签。使用协议委托模式好吗?目前无法正常工作,时间尚在,但无法在第一个VC中更新视图

我的协议结构

protocol ViewControllerDelegate: class {
    func changeLabelText(textToPass: String)
}


在第一个viewController中

class ViewController: UIViewController, ViewControllerDelegate {


    @IBOutlet weak var mainLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }


    func changeLabelText(textToPass: String) {
        self.mainLabel.text = textToPass
        self.view.layoutIfNeeded()
    }

    @IBAction func buttonTapped(_ sender: UIButton) {

        let nextVC = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
        nextVC.delegateSubscriber = self
        present(nextVC, animated: true, completion: nil)
    }

}


在secondVC中

class SecondViewController: UIViewController {

    //MARK: speed timer feature 1/3
    private weak var timer: Timer?
    private var timerDispatchSourceTimer : DispatchSourceTimer?

    weak var delegateSubscriber : ViewControllerDelegate?

    @IBOutlet weak var myTxtField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        startTimer(every: 1)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        print("appeared")
        stopTimer()

    }

    private func startTimer(every timeInterval: TimeInterval) {
        if #available(iOS 10.0, *) {
            timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true) { [weak self] _ in

                let dateToPass = Date().description
                print(dateToPass)
                self?.delegateSubscriber?.changeLabelText(textToPass: dateToPass)

            }
        }
    }

    //MARK: speed timer feature 3/3
    private func stopTimer() {
        timer?.invalidate()
        //timerDispatchSourceTimer?.suspend() // if you want to suspend timer
        timerDispatchSourceTimer?.cancel()
    }

    @IBAction func buttonTapped(_ sender: UIButton) {

//        delegateSubscriber?.changeLabelText(textToPass: self.myTxtField.text ?? "error")

        dismiss(animated: true, completion: nil)
    }
}

最佳答案

只需从[weak self]闭包中删除Timer

timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
    let dateToPass = Date().description
    print(dateToPass)
    self.delegateSubscriber?.changeLabelText(textToPass: dateToPass)
}


...那么self不是可选的

关于swift - 快速如何从第二个VAI协议(protocol)和委托(delegate)模式中的逻辑更新第一 Controller ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53792680/

10-11 22:42