如何从Swift中的TabBarController访问viewcontroller的NSTimer

时间:2016-01-12 12:55:17

标签: swift uitabbarcontroller

我是Swift的新手。我的ios应用程序中有一个Tab Bar Controller。我在我的第一个标签中启动NSTimer,其名称为HomePageViewController,如下所示:

 override func viewDidLoad() {
        super.viewDidLoad(){
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
}

func stopTimer(){
        print("stop timer")
        self.timer?.invalidate()
        self.timer=nil
    }

    func reStartTimer(){
        print("restart timer")
        timer?.invalidate()
        timer=nil
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
    }

我在TabBarController.swift中的didSelectItem方法是:

    override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

if item == (self.tabBar.items![0]){
//necessary operation
}

else {
homePageVC.stopTimer()
    }

但计时器不会停止。如何从TabBarViewController中停止计时器?

2 个答案:

答案 0 :(得分:0)

您应该使计时器无效。请参阅文档here

if item == (self.tabBar.items![0]){
    //necessary operation
} else {
    homePageVC.invalidate()
}

答案 1 :(得分:0)

好的我修复了问题:

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        let homePageVC = self.viewControllers![0] as! HomePageViewController

        if item == (self.tabBar.items![0]){
            if (lastSelectedTabItem==0){
            }
            else{
                homePageVC.reStartTimer()
            }
        }
        else {
            homePageVC.stopTimer()
        }

        if(item.title=="Tab1"){
            lastSelectedTabItem=0
        }
        else if(item.title=="Tab2"){
            lastSelectedTabItem=1
        }
        else if(item.title=="Tab3"){
            lastSelectedTabItem=2
        }
        else {
            lastSelectedTabItem=3
        }

    }