如何弹出初始视图控制器

时间:2017-09-02 13:21:42

标签: ios swift

假设我有两个视图控制器,View controller A和View controller B

class ViewControllerA: UIViewController {
     override func viewDidLoad() {
        super.viewDidLoad()
        // it runs this function every 5 seconds
         Timer.scheduledTimer(5, target: self,selector: #selector(ViewControllerA.printNumber), userInfo: nil, repeats: true)
    }

    @IBAction func callViewControllerBButtonClicked(_ sender: UIButton) {
         if let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerBID") as? ViewControllerB {

                self.present(vc, animated: true, completion: nil)
        }

    }

    func printNumber() {
      print(0)
    }
}

每当有人点击callViewControllerBButtonClicked()按钮时,它都会实例化一个新的视图控制器,它是ViewControllerB,并将它呈现在ViewControllerA之上。我现在面临的问题是即使我已经在ViewControllerB上,它仍然运行此功能

Timer.scheduledTimer(5, target: self,selector: #selector(ViewControllerA.printNumber), userInfo: nil, repeats: true)

如何弹出ViewControllerA?

1 个答案:

答案 0 :(得分:0)

试试这段代码 -

class ViewControllerA: UIViewController {
     var timer : Timer!
     override func viewDidLoad() {
        super.viewDidLoad()
        // it runs this function every 5 seconds
        timer = Timer.scheduledTimer(5, target: self,selector: #selector(ViewControllerA.printNumber), userInfo: nil, repeats: true)
    }

    @IBAction func callViewControllerBButtonClicked(_ sender: UIButton) {
         if let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerBID") as? ViewControllerB {
            timer.invalidate()
            self.present(vc, animated: true, completion: nil)
        }

    }

    func printNumber() {
      print(0)
    }
}