Search code examples
viewcalluibarbuttonitem

Call UIBarButtonItem from other view controller


I want to implement a UIBarButtonItem on a Navigation Controller (father) which have embed a TabBar Controller with three tabs, and I want to implement an action on it, but that can be called from all views instead to implement different UIBarButtonItem on each view.

What I want is when the UIBarButtonItem tapped show an ActionSheet that will be the same on all views no matter in which view the user be.

Can you help me with this, I'm really new on iOS and Swift Programming.

Thank you!


Solution

  • Ok, I think that I answer my own question, and was very easy. I just create an custom view controller file and associated with my TabBar View on my history board and add action for the UIButtonBarItem like this:

    import UIKit
    
    class CustomTabBarViewControler: UITabBarController {
    
    
        @IBAction func showActionSheet(sender: UIBarButtonItem) {
    
            let myActionSheet = UIAlertController(title: "Log in", message: "How do you want to log in", preferredStyle: UIAlertControllerStyle.ActionSheet)
    
            let fbLoginButton = UIAlertAction(title: "Facebook", style: UIAlertActionStyle.Default)
                { (ACTION) in
                    print("Facebook Button Tapped")
            }
            let googlePlusButton = UIAlertAction(title: "Google Plus", style: UIAlertActionStyle.Default) {
                (ACTION) in
                print("Google Plus Button Tapped")
            }
            let twitterButton = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default) {
                (ACTION) in
                print("Twitter Button Tapped")
            }
    
            let cancelButton = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
                (ACTION) in
                print("Cancel Button Tapped")
            }
    
            myActionSheet.addAction(fbLoginButton)
            myActionSheet.addAction(googlePlusButton)
            myActionSheet.addAction(twitterButton)
            myActionSheet.addAction(cancelButton)
    
            self.presentViewController(myActionSheet, animated: true, completion: nil)
        }
    
    }
    

    And with this works fine for me.