Setting Selected Image in Tab Bar Controller with Storyboard

Setting Selected Image in Tab Bar Controller with Storyboard

You can use storyboard to set selected image of tabbar. I tried and it worked for me.
Select the UITabbarItem and add a run-time attribute 'selectedImage', select Type as 'Image' and give the name of your image as its value.

Setting selected image of Tabbar using storyboard

I am using XCode 6.0 and my minimum deployment target is iOS 8.0.

How to set tab bar icon and title for a Navigation controller in different Storyboard which has reference in Main.storyboard?

Select your navigation controller in second storyboard and open attributes inspector. At the top you'll see bottom bar option with inferred selected by default. Change that to translucent tab bar. Now from object library drag and drop "Tab Bar Item" on that translucent tab bar that just appeared. Now you can set the title and icon for that tab.

Sample Image

Change Image when clicking tabbar

There is function you can use to detect selected tab in the UITabBarControllerDelegate

tabBarController(_ tabBarController: UITabBarController, 
didSelect viewController: UIViewController)

(Swift) Tab Bar Item: Custom Selected Image with Rendering asOriginal is Not Showing

I extend UITabBarController:

extension UITabBarController {

func updateTabBarItem(tab: Int, image: UIImage?) {

guard let tabItems = tabBar.items, tab < tabItems.count && tab >= 0
else { return }

let tabItem = tabItems[tab]
tabItem.image = image?.withRenderingMode(.alwaysOriginal)
tabItem.selectedImage = tabItem.image

}

}

This will help to access the tabBar.items without loading any view controllers (except the first view controller of the tab 0).

class MyViewController: UIViewController {

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabBarController?.updateTabBarItem(tab: 1, image: UIImage(named: "selected-image")) // update the second tab's image here (just for example)
}

}

For example, if you want to change the tab 2 selected image, make a break point on viewDidLoad: on the second view controller, you will find the break point doesn't hit, that's why the tab item's image wouldn't be updated.

Setting Selected Image in Tab Bar Controller with Storyboard ios7


UITabBar *tabBar = self.tabBar;

UITabBarItem *targetTabBarItem = [[tabbar items] objectAtIndex:0]; // whichever tab-item
UIImage *selectedIcon = [UIImage imageNamed:@"name-of-selected-image.png"];
[targetTabBarItem setSelectedImage:selectedIcon];


Related Topics



Leave a reply



Submit