Search code examples
iosswiftuitabbaritem

Set ios tabbar item programmatically


I have four tab items that I set via storyboard but I have just one tab bar that I would like to set programmatically because I want that last tab bar item to be my profile picture. Is there a way I can set just that one tab bar item programmatically in the ProfileViewController without having to set the other three tab bar items programmatically.

I want to set this to the tabbar item but it is coming up blank:

override func awakeFromNib() {

        super.awakeFromNib()
        self.tabBarItem.title = "MY ACCOUNT"
      //  self.tabBarItem.image = UIImage(named: "Speech Bubble Filled-50")

        if let postProfile = self.loggedInUserUid {

            let imageRef = FIRStorage.storage().reference().child((loggedInUserUid)!+"/profile_pic.jpg")

            imageRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) -> Void in
                if error != nil {
                    print(error)
                    return
                }
                DispatchQueue.main.async(execute: { () -> Void in
                    let image = UIImage(data: data!)
                    self.tabBarItem.image = image
                })

            }).resume()
}}

Solution

  • A view controller can set its own tab image after being loaded from a storyboard. You can do it in awakeFromNib:

    class SecondViewController: UIViewController {
    
        override func awakeFromNib() {
            super.awakeFromNib()
            self.tabBarItem.image = UIImage(named: "star")
        }
    
    }
    

    Result:

    tab bar with star image

    You might want to do a better job than I did of sizing the image…