FS.O5
FS.O5

Reputation: 297

Detecting when tabBar item is pressed when is page

I have a UITabBar with 4 tabs.

I want to that a specific function will be called in each ViewController of the tab when the tabBarItem is pressed twice (like, the user is now on ProfileVC and presses on Profile item, I want to refresh the view).

How can I detect when the user pressed on the tab that he is in its view now?

Thank you!

Upvotes: 1

Views: 570

Answers (1)

LIH
LIH

Reputation: 933

One option is do the refreshing inside viewWillAppear() method. And the second one is considerably long.

In parent view controller

protocol ParentDelegate {
     func refresh()
}

class LandingViewController: UIViewController, UITabBarDelegate {

    var delegate: ParentDelegate?
    var selectedItem: UITabBarItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBar.delegate = self
        self.selectedItem = self.tabBar.selectedItem
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "SegueNameForDestinationViewController1" {

            if let vc = segue.destinationViewController as? YourDestinationViewController1 {
                self.delegate = vc.self
            }

        } else if segue.identifier == "SegueNameForDestinationViewController2" {

            if let vc = segue.destinationViewController as? YourDestinationViewController2 {
                self.delegate = vc.self
            }

        }
    }

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

        if self.selectedItem == item {
            self.delegate?.refresh()
        }
        self.selectedItem = item
    }
}

In each tab view controller,

class TabViewController: UIViewController, ParentDelegate {

    func refresh() {
        //write your code here
    }
}

Upvotes: 1

Related Questions