August 2019 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

12 Aug 2019

Add ImageView (profile picture) to TabBar item (UITabBarController) using swift 5 - iOS

8/12/2019 10:39:00 am 1
Add ImageView (profile picture) to TabBar item (UITabBarController) using swift 5 - iOS

Adding image view to tab bar is quite easy.

First create new single view application. Embed ViewController inside tabBarController and add new tab name it my account.

After doing all above stuff you will see output as the following image


Embed ViewController inside tabBarController and add new tab name it my account.

Now drag some sample image to image assets and name it as profile.

Add the following extension to your project, you can add after the ViewController.swift class ends.

extension UITabBarController {
    
    func addSubviewToLastTabItem(_ imageName: String) {
        if let lastTabBarButton = self.tabBar.subviews.last, let tabItemImageView = lastTabBarButton.subviews.first {
            if let accountTabBarItem = self.tabBar.items?.last {
                accountTabBarItem.selectedImage = nil
                accountTabBarItem.image = nil
            }
            let imgView = UIImageView()
            imgView.frame = tabItemImageView.frame
            imgView.layer.cornerRadius = tabItemImageView.frame.height/2
            imgView.layer.masksToBounds = true
            imgView.contentMode = .scaleAspectFill
            imgView.clipsToBounds = true
            imgView.image = UIImage(named: imageName)
            self.tabBar.subviews.last?.addSubview(imgView)
        }
    }
}

Now open ViewController.swift file add the following method:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.tabBarController?.addSubviewToLastTabItem("profile")
}

That's it, Now run the app you will the desired results as follow:

Add ImageView (profile picture) to TabBar item (UITabBarController) using swift 5 - iOS

Read More

Post Top Ad