2017-09-02 37 views
0

让说我有两个视图控制器,查看控制器A和视图控制器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?

+0

只是因为你现在VC-B并不意味着你的VC-A停止运行的定时器。你不能弹出一个呈现另一个视图控制器的视图控制器。你正在使用“self.present”,self = VC-A,如果VC-A提供了一些内容,并且你想同时弹出它,那么这是合乎逻辑的?你需要阅读教程并研究一切如何运作,所以你可以发布一个问题,表明你至少已经完成了作业。如果你没有研究过事物的运作方式,给你一个解决方案不会教你或者有什么好处,反之则相反。无论如何你在这里得到了答案。 GL – 2017-09-02 13:54:22

+0

@Sneak我应该阅读什么?我应该怎么做才能停止View ControllerA上的定时器? – sinusGob

+0

您需要阅读UIViewControllers的工作原理。或者您正在呼叫/编码的方法,即存在。 https://developer.apple.com/documentation/uikit/uiviewcontroller/1621380-presentviewcontroller和你的计时器:https://developer.apple.com/documentation/foundation/timer/1415405-invalidate。例如,您可以在呈现之前使您的计时器无效(如下面的人回答)。或者,您可以使viewDidDissapear上的计时器无效https://developer.apple.com/documentation/uikit/uiviewcontroller/1621477-viewdiddisappear。只要谷歌mehods你会发现所有的答案 – 2017-09-02 14:00:08

回答

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) 
    } 
} 
相关问题