【问题标题】:How to pop the initial view controller如何弹出初始视图控制器
【发布时间】:2017-09-02 21:31:44
【问题描述】:

假设我有两个视图控制器,视图控制器 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?

【问题讨论】:

  • 仅仅因为您提供了 VC-B 并不意味着您的 VC-A 停止运行其计时器。而且您不能弹出呈现另一个视图控制器的视图控制器。您正在使用 "self.present" , self = VC-A ,如果 VC-A 展示了某些东西,并且您想同时弹出它,那这合乎逻辑吗?您需要阅读教程并研究一切如何运作,这样您就可以发布一个问题,表明您实际上至少完成了作业。如果您没有研究过事情是如何运作的,那么给您一个解决方案不会教给您或对您有任何好处,而是相反。无论如何,你在这里得到了答案。总帐
  • @Sneak 那我应该读什么?我应该怎么做才能停止 View ControllerA 上的计时器?
  • 您需要了解 UIViewControllers 的工作原理。或者您至少调用/编码的方法,即存在。 developer.apple.com/documentation/uikit/uiviewcontroller/… 和你的计时器:developer.apple.com/documentation/foundation/timer/…。例如,您可以在演示之前使您的计时器无效(正如下面有人回答的那样)。或者您可以使 viewDidDissapear developer.apple.com/documentation/uikit/uiviewcontroller/… 上的计时器无效。谷歌搜索方法你会找到所有答案
  • 还要确保在弹出 VC-A 之前使计时器无效,如果您这样做的话,让计时器循环运行并在不使计时器无效的情况下弹出 VC 将使您的 VC-A 继续运行在后台直到计时器停止,这将保持一个保留周期stackoverflow.com/questions/3478361/…

标签: ios swift


【解决方案1】:

试试这个代码 -

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)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    相关资源
    最近更新 更多