简体   繁体   中英

Working with Tabbar ios Swift

I am working on UITabBar using Swift 4 where I want different icon for selected and un-selected tab.

But UITabBar is changing tintColor only and I am not able to set different image for selected and un-selected tab.

So if it is possible to set different icon for selected and un-selected tab please let me know.

This is what I have tried :

let item1 = self.storyboard?.instantiateViewController(withIdentifier: "DashboardViewController")
let icon1 = UITabBarItem(title: "", image: UIImage(named: "first_unselected"), selectedImage: UIImage(named: "first_selected"))
item1?.tabBarItem = icon1

The problem is not in the way how you create an UITabBarItem - I've tested that and it works. So I guess the problem is where you set it up:

let item1 = self.storyboard?.instantiateViewController(withIdentifier: "DashboardViewController")

You have to realize that this line of code will create a NEW instance of the DashboardViewController , which is NOT the one presented on the screen. So unless somewhere later you present item1 , then of course those line of code will not have any impact on the screen.

What you want to do is to configure the instance that is presented on the screen (the one loaded automatically by the storyboards). I think the best and the easiest way is to add the configuration code into initializers of the DashboardViewController - this way ANY instance of the DashboardViewController will behave properly - so the one presented on the screen too.

Take the following code as an example:

import UIKit

class DashboardViewController: UIViewController {

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

        initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        initialize()
    }

    func initialize() {
        let icon1 = UITabBarItem(title: "", image: #imageLiteral(resourceName: "first_unselected"), selectedImage: #imageLiteral(resourceName: "first_selected"))
        self.tabBarItem = icon1
    }
}

According to the documentation you should use selectedImage property in UITabBarItem.

  let tabBarButton = UITabBarItem(title: "", image: 
  UIImage(named:"image"))
  tabBarButton.selectedImage: UIImage(named: "selected_image")

By default, the actual unselected and selected images are automatically >created from the alpha values in the source images. To prevent system >coloring, provide images with alwaysOriginal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM