UIBarButtonItem not working in ios11 - uinavigationbar

Long story short iOS10 left, right buttons, custom label working without issues, iOS11 none of the showing. I've read elsewhere that I need to add constraints for the buttons but that is not helping. Code called in viewDidLoad().
self.connectionButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0,0.0,74.0,29.0)];
[self.connectionButton.widthAnchor constraintEqualToConstant:74].active = YES;
[self.connectionButton.heightAnchor constraintEqualToConstant:29].active = YES;
self.connectionButton.backgroundColor = [UIColor yellowColor];
UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:self.connectionButton];
self.navigationItem.rightBarButtonItem = buttonItem;
Appearance:
[[UINavigationBar appearance] setTranslucent:YES];
[[UINavigationBar appearance] setShadowImage:[UIImage new]];
[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundColor:[UIColor clearColor]];
When I check the frame during run time it's correct (0,0,74,29). No button is shown in the bar though.
XCode 9 beta 8, not working on either device nor simulator.

With more testing I found out that the navigation bar doesn't show anything - not even the title in default appearance. After hours wasted on commenting/uncommenting pieces of unrelated code I found the culprit:
override var traitCollection: UITraitCollection {
var horizTraitCollection = UITraitCollection(horizontalSizeClass: .regular)
if view.bounds.width < view.bounds.height {
horizTraitCollection = UITraitCollection(horizontalSizeClass: .compact)
}
return UITraitCollection(traitsFrom: [horizTraitCollection, UITraitCollection(verticalSizeClass: super.traitCollection.verticalSizeClass)])
}
This is what I use override size class for portrait/landscape presentation. IMO completely unrelated to navigation bar appearance. No idea why is it breaking the navigation bar or how to fix it .
EDIT: After some tweaking I was able to get it working on iPads but not iPhones. After some more tweaking I got it working on iPhone as well:
override var traitCollection: UITraitCollection {
if UIDevice.current.userInterfaceIdiom == .pad {
var horizTraitCollection = UITraitCollection(horizontalSizeClass: .regular)
if UIDevice.current.orientation.isPortrait {
horizTraitCollection = UITraitCollection(horizontalSizeClass: .compact)
}
return UITraitCollection(traitsFrom: [horizTraitCollection, UITraitCollection(verticalSizeClass: super.traitCollection.verticalSizeClass)])
}
return super.traitCollection
}

Related

controller navigationItem.leftBarButtonItem changes color in IOS7

I have an image that is assigned to the navigationItem.leftBarButtonItem on IOS7. When I get it from the designer it looks fine on the navigation bar's background. But when I implement it in IOS7 it becomes pale and almost disappears.
This is how it's being set up:
UIBarButtonItem *button = [[barButtonItemClass alloc] initWithImage:[UIImage imageNamed:#"nav_menu_icon.png"] style:UIBarButtonItemStyleBordered target:self action:#selector(showLeft:)];
viewController.navigationItem.leftBarButtonItem = button;
This is how it should look (image came from my designer):
And this is how it looks when implemented (on the simulator or a phone):
What's the solution?
You should set the tint color of the navigation bar to tint all items in the bar.
A nice solution is to use the UIAppearanceprotocol introduced in iOS 5.
In you AppDelegate's applicationDidFinishLaunching method put the following code:
[[UINavigationBar appearance] setTintColor: [UIColor whiteColor]];
Note, I am currently not able to try the code.
Cheers!
this works fine for me :
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithImage:backButtonImage style:UIBarButtonItemStyleBordered target:self action:#selector(backBtnAction)];
customItem.imageInsets = UIEdgeInsetsMake(0.0, -10, 0, 0);// For adjusting the image
[customItem setBackgroundVerticalPositionAdjustment:+3.0f forBarMetrics:UIBarMetricsDefault];
[self.navigationItem setHidesBackButton:YES];// Hide the Default back button before set custom
[self.navigationItem setLeftBarButtonItem: customItem];
Hopefully, causes might be with the Tint
Try this, may help you ;
// Solve your frame issue.
UIImage * bgImg = [UIImage imageNamed:#"nav_menu_icon.png"];
UIButton *leftButton = [[UIButton alloc] initWithFrame: CGRectMake(x, y, bgImg.size.width, bgImg.size.width)];
viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
Also change the tintColour to clear colour.

Center elements vertically inside UINavigationBar with custom height

I'm developing an iOS 6 and 7 app that requires the navigation bar to be taller than the usual 44/64 pts
I've searched high and low and so far it seems the cleanest solution is to use a category (or subclass) and implement the - (CGSize)sizeThatFits:(CGSize)size method to return a different size.
This works fine in just making , however doing this causes all the items inside to rest at the bottom of the navigation bar, while I'd like to have them centered.
I have tried using the Appearance Proxy protocol to define vertical offsets for the buttons, specifically this code
[[UIBarButtonItem appearance] setBackgroundVerticalPositionAdjustment: -10 forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setBackButtonBackgroundVerticalPositionAdjustment: -10 forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setTitleVerticalPositionAdjustment: -10 forBarMetrics: UIBarMetricsDefault];
Works just fine on iOS 6, producing this result
But doesn't work on iOS 7, giving me this instead.
I have read around that under iOS 7 the adjustments only work when using custom views but it seems odd to me, especially considering that setBackButtonTitlePositionAdjustment:forBarMetrics: actually moves the text for the back button up, but not the chevron and that the title actually does nudge up.
I've also tried going for a subclassing route, using layoutSubviews to move down the views inside the UINavigationBar.
This works, but of course when a new view controller is pushed the buttons jump around during the transition.
Am I missing something? Thanks in advance
UPDATE I have edited the description to make it clearer that my issue is with what's inside the bar, not the bar itself.
The cleanest solution I've found to this problem was to use my own subclass of UINavigationBar and center the buttons vertically by overriding the layoutSubviews method:
- (void)layoutSubviews
{
[super layoutSubviews];
NSArray *subviews = self.subviews;
for (UIView *view in subviews) {
if ([view isKindOfClass:[UIButton class]]) {
view.frame = ({
CGRect frame = view.frame;
CGFloat navigationBarHeight = CGRectGetHeight(self.frame);
CGFloat buttonHeight = CGRectGetHeight(view.frame);
frame.origin.y = (navigationBarHeight - buttonHeight) / 2.0f;
frame;
});
}
}
}
To make a UINavigationController use your subclass of UINavigationBar you can use the initWithNavigationBarClass:toolbarClass: initialiser:
UINavigationController *navigationController = [[UINavigationController alloc] initWithNavigationBarClass:[MyNavigationBar class] toolbarClass:nil];
Did you try to add the following code to your viewDidLoad Method :
if ([self respondsToSelector:#selector(edgesForExtendedLayout)])
self.edgesForExtendedLayout = UIRectEdgeNone;
It is quickly explained in Apple migrating to iOS 7 Documentation : https://developer.apple.com/library/ios/documentation/userexperience/conceptual/TransitionGuide/AppearanceCustomization.html
//it's leave the status-bar height above.
There is a quick crack to this, unless you find the proper solution, this would definitely work ;)
Check for system running iOS7.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
{
// Add below code
}
Add Label to the Navigation Bar :
UINavigationBar *bar = [self.navigationController navigationBar];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(110, 55, 150, 20)]; //Set the frame appropriate to your screen
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:14];
label.adjustsFontSizeToFitWidth = NO;
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor blackColor];
label.highlightedTextColor = [UIColor blackColor];
[bar addSubview:label];
Swift 3 version of Tiago his answer
override func layoutSubviews() {
super.layoutSubviews()
subviews.filter { (subview) -> Bool in
return subview is UIButton
}.forEach { (subview) in
subview.center.y = frame.height / 2
}
}
Adjusting the titleView vertical postion
setTitleVerticalPositionAdjustment(-10, for: .default)
You can change size of navigation bar with just changing it's frame:
CGRect navigationBarFrame = self.navigationController.navigationBar.frame;

how to set UIBarButtonItem selected or highlighted image or tint colours in iOS 7?

How to provide normal state and selected/highlighted state images to uibarbuttonitem in iOS 7? Is there any way to provide tint colour for both normal and selected/highlighted state of uibarbuttonitem?
I don't want to use uibutton as a view for uibarbuttonitem! Any elegant solution would be highly appreciated.
You can use a UIButton as a customView of a UIBarButtonItem and have two different background images for a normal and selected state of the UIButton. Then when the button is tapped, you can just set the selected state to YES or NO.
// Build right bar button
UIImage *normalButtonImage = [UIImage imageNamed:#"normal-button"];
UIImage *selectedButtonImage = [UIImage imageNamed:#"selected-button"];
CGRect rightButtonFrame = CGRectMake(0, 0, normalButtonImage.size.width,
normalButtonImage.size.height);
UIButton *rightButton = [[UIButton alloc] initWithFrame:rightButtonFrame];
[rightButton setBackgroundImage:normalButtonImage forState:UIControlStateNormal];
[rightButton setBackgroundImage:selectedButtonImage forState:UIControlStateSelected];
[rightButton addTarget:self action:#selector(rightBarButtonPress)
forControlEvents:UIControlEventTouchDown];
[orientationButton setShowsTouchWhenHighlighted:YES];
[orientationButton setSelected:NO];
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
[self.navigationItem setRightBarButtonItem:rightBarButton];
Then your in method for when the button is clicked, change the state
- (void)rightBarButtonPress
{
//toggle selected state of button
UIBarButtonItem *rightBarButton = self.navigationItem.rightBarButtonItem;
UIButton *button = (UIButton *)rightBarButton.customView;
[button setSelected:!button.selected];
//do whatever else you gotta do
}
You can do this using the UIAppearance Protocol Reference
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], UITextAttributeTextColor, [UIColor clearColor], UITextAttributeTextShadowColor, nil];
[[UIBarButtonItem appearance] setTitleTextAttributes:options forState:UIControlStateNormal];
You might also have to use:
[[UINavigationBar appearance] setTintColor:[UIColor redColor]];
According to this answer, I did something extra and kind of have an answer for you here. I have my custom UITabBarController, which is linked with my UITabBarController in the StoryBoard file. So in order to remove the automatic tint provided by iOS when the TabBar is unselected, I ended up removing it in this manner. The images can be a vast variety of images but just in the way recommended here. Here it goes:
NSArray *navConArr = self.viewControllers;//self is custom UITabBarController
UINavigationController *naviOne = [navConArr objectAtIndex:0];//I have 3 different tabs, objectAtIndex:0 means the first tab navigation controller
UITabBarItem *naviBtn = naviOne.tabBarItem;
UIImage *image = [[UIImage imageNamed:#"iconNaviOne"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[naviBtn setSelectedImage:image];
[naviBtn setImage:image];
So when moving from this tab to the other one and leaving this in the unselected (gray as default) tint, you can set it to the image provided. Thankfully, this works like a charm (:
Here is Swift 4 solution:
private var barButtonItem: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
let barButtonItem = UIBarButtonItem(image: UIImage(named: "YourImage"), style: .plain, target: self, action: #selector(handleBarButtonAction))
navigationItem.rightBarButtonItem = barButtonItem
self.barButtonItem = barButtonItem
}
#objc
private func handleBarButtonAction() {
if barButtonItem?.image == UIImage(named: "YourImage") {
barButtonItem?.image = UIImage(named: "YourSelectedImage")
} else {
barButtonItem?.image = UIImage(named: "YourImage")
}
}
AFAIK there is no native/elegant solution to do this, what I've done is tracking the state of the button and based on that change the tintColor
#objc func handleButton() {
if yourButtonIsSelected {
yourButton.tintColor = unselectedColor
} else {
yourButton.tintColor = selectedColor
}
}
Notice that there is no way to know if a UIBarButtonItem is selected or not, thus you will need to provide this too (yourButtonIsSelected on my example)
Swift 5.x
guard let button = self?.navigationItem.rightBarButtonItem?.customView as? UIButton else { return }
// button.isSelected = #your condition here
// button.tintColor = #your condition here

How to change navigation bar color in iOS 7 or 6?

I want to change the color of the navigation bar color, but I'm not sure whether or not I should change the tint or the background. I know iOS 7 is going for a more flat design (even recommending removing gradients), but I am having trouble deciphering the two. Even if I set a background color, it doesn't do anything.
In this image, the background is set to green, but the bar is still blue:
The behavior of tintColor for bars has changed on iOS 7.0. It no longer affects the bar's background and behaves as described for the tintColor property added to UIView.
To tint the bar's background, please use -barTintColor.
navController.navigationBar.barTintColor = [UIColor navigationColor];
If you want to have a solid color for your navigation bar in iOS 6 similar to iOS 7 use this:
[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundColor:[UIColor greenColor]];
in iOS 7 use the barTintColor like this:
navigationController.navigationBar.barTintColor = [UIColor greenColor];
or
[[UINavigationBar appearance] setBarTintColor:[UIColor greenColor]];
// In ios 7 :-
[self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
// In ios 6 :-
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
The background color property is ignored on a UINavigationBar, so if you want to adjust the look and feel you either have to use the tintColor or call some of the other methods listed under "Customizing the Bar Appearance" of the UINavigationBar class reference (like setBackgroundImage:forBarMetrics:).
Be aware that the tintColor property works differently in iOS 7, so if you want a consistent look between iOS 7 and prior version using a background image might be your best bet. It's also worth mentioning that you can't configure the background image in the Storyboard, you'll have to create an IBOutlet to your UINavigationBar and change it in viewDidLoad or some other appropriate place.
One more thing, if you want to change the navigation bg color in UIPopover you need to set barStyle to UIBarStyleBlack
if([UINavigationBar instancesRespondToSelector:#selector(barTintColor)]){ //iOS7
navigationController.navigationBar.barStyle = UIBarStyleBlack;
navigationController.navigationBar.barTintColor = [UIColor redColor];
}
Here is how to set it correctly for both iOS 6 and 7.
+ (void)fixNavBarColor:(UINavigationBar*)bar {
if (iosVersion >= 7) {
bar.barTintColor = [UIColor redColor];
bar.translucent = NO;
}else {
bar.tintColor = [UIColor redColor];
bar.opaque = YES;
}
}
The complete code with version checking.
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
// do stuff for iOS 7 and newer
[self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
}
else {
// do stuff for older versions than iOS 7
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
}
You can check iOS Version and simply set the tint color of Navigation bar.
if (SYSTEM_VERSION_LESS_THAN(#"7.0")) {
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.9529 green:0.4392 blue:0.3333 alpha:1.0];
}else{
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.9529 green:0.4392 blue:0.3333 alpha:1.0];
self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
Based on posted answered, this worked for me:
/* check for iOS 6 or 7 */
if ([[self navigationController].navigationBar respondsToSelector:#selector(setBarTintColor:)]) {
[[self navigationController].navigationBar setBarTintColor:[UIColor whiteColor]];
} else {
/* Set background and foreground */
[[self navigationController].navigationBar setTintColor:[UIColor whiteColor]];
[self navigationController].navigationBar.titleTextAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:[UIColor blackColor],UITextAttributeTextColor,nil];
}
you can add bellow code in appdelegate.m .if your app is navigation based
// for background color
[nav.navigationBar setBarTintColor:[UIColor blueColor]];
// for change navigation title and button color
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],
NSForegroundColorAttributeName,
[UIFont fontWithName:#"FontNAme" size:20],
NSFontAttributeName, nil]];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
Insert the below code in didFinishLaunchingWithOptions() in AppDelegate.m
[[UINavigationBar appearance] setBarTintColor:[UIColor
colorWithRed:26.0/255.0 green:184.0/255.0 blue:110.0/255.0 alpha:1.0]];
I'm using following code (in C#) to change the color of the NavigationBar:
NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.Default);
NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.LandscapePhone);
NavigationController.NavigationBar.BackgroundColor = UIColor.Green;
The trick is that you need to get rid of the default background image and then the color will appear.
If you want to change a color of a navigation bar, use barTintColor property of it. In addition, if you set any color to tintColor of it, that affects to the navigation bar's item like a button.
FYI, you want to keep iOS 6 style bar, make a background image looks like previous style and set it.
For more detail, you can get more information from the following link:
https://developer.apple.com/library/ios/documentation/userexperience/conceptual/TransitionGuide/AppearanceCustomization.html
In iOS7, if your navigation controller is contained in tab bar, splitview or some other container, then for globally changing navigationbar appearance use following method ::
[[UINavigationBar appearanceWhenContainedIn:[UITabBarController class],nil] setBarTintColor:[UIColor blueColor]];
Try the code below in the - (void)viewDidLoad of your ViewController.m
[[[self navigationController] navigationBar] setTintColor:[UIColor yellowColor]];
this did work for me in iOS 6.. Try it..
I'm not sure about changing the tint vs the background color but this is how you change the tint color of the Navigation Bar:
Try this code..
[navigationController.navigationBar setTintColor:[UIColor redColor]; //Red as an example.

Changing Tint / Background color of UITabBar

The UINavigationBar and UISearchBar both have a tintColor property that allows you to change the tint color (surprising, I know) of both of those items. I want to do the same thing to the UITabBar in my application, but have found now way to change it from the default black color. Any ideas?
iOS 5 has added some new appearance methods for customising the look of most UI elements.
You can target every instance of a UITabBar in your app by using the appearance proxy.
For iOS 5 + 6:
[[UITabBar appearance] setTintColor:[UIColor redColor]];
For iOS 7 and above, please use the following:
[[UITabBar appearance] setBarTintColor:[UIColor redColor]];
Using the appearance proxy will change any tab bar instance throughout the app. For a specific instance, use one of the new properties on that class:
UIColor *tintColor; // iOS 5+6
UIColor *barTintColor; // iOS 7+
UIColor *selectedImageTintColor;
UIImage *backgroundImage;
UIImage *selectionIndicatorImage;
I have been able to make it work by subclassing a UITabBarController and using private classes:
#interface UITabBarController (private)
- (UITabBar *)tabBar;
#end
#implementation CustomUITabBarController
- (void)viewDidLoad {
[super viewDidLoad];
CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
UIView *v = [[UIView alloc] initWithFrame:frame];
[v setBackgroundColor:kMainColor];
[v setAlpha:0.5];
[[self tabBar] addSubview:v];
[v release];
}
#end
I have an addendum to the final answer. While the essential scheme is correct, the trick of using a partially transparent color can be improved upon. I assume that it's only for letting the default gradient to show through. Oh, also, the height of the TabBar is 49 pixels rather than 48, at least in OS 3.
So, if you have a appropriate 1 x 49 image with a gradient, this is the version of viewDidLoad you should use:
- (void)viewDidLoad {
[super viewDidLoad];
CGRect frame = CGRectMake(0, 0, 480, 49);
UIView *v = [[UIView alloc] initWithFrame:frame];
UIImage *i = [UIImage imageNamed:#"GO-21-TabBarColorx49.png"];
UIColor *c = [[UIColor alloc] initWithPatternImage:i];
v.backgroundColor = c;
[c release];
[[self tabBar] addSubview:v];
[v release];
}
When you just use addSubview your buttons will lose clickability, so instead of
[[self tabBar] addSubview:v];
use:
[[self tabBar] insertSubview:v atIndex:0];
There is no simple way to do this, you basically need to subclass UITabBar and implement custom drawing to do what you want. It is quite a bit of work for the effect, but it may be worth it. I recommend filing a bug with Apple to get it added to a future iPhone SDK.
Following is the perfect solution for this. This works fine with me for iOS5 and iOS4.
//---- For providing background image to tabbar
UITabBar *tabBar = [tabBarController tabBar];
if ([tabBar respondsToSelector:#selector(setBackgroundImage:)]) {
// ios 5 code here
[tabBar setBackgroundImage:[UIImage imageNamed:#"image.png"]];
}
else {
// ios 4 code here
CGRect frame = CGRectMake(0, 0, 480, 49);
UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
UIImage *tabbag_image = [UIImage imageNamed:#"image.png"];
UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
tabbg_view.backgroundColor = tabbg_color;
[tabBar insertSubview:tabbg_view atIndex:0];
}
On iOS 7:
[[UITabBar appearance] setBarTintColor:[UIColor colorWithRed:(38.0/255.0) green:(38.0/255.0) blue:(38.0/255.0) alpha:1.0]];
I also recommend setting first depending on your visual desires:
[[UITabBar appearance] setBarStyle:UIBarStyleBlack];
The bar style puts a subtle separator between your view content and your tab bar.
[[self tabBar] insertSubview:v atIndex:0];
works perfectly for me.
for me its very simple to change the color of Tabbar like :-
[self.TabBarController.tabBar setTintColor:[UIColor colorWithRed:0.1294 green:0.5686 blue:0.8353 alpha:1.0]];
[self.TabBarController.tabBar setTintColor:[UIColor "YOUR COLOR"];
Try this!!!
[[UITabBar appearance] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];
for just background color
Tabbarcontroller.tabBar.barTintColor=[UIColor redcolour];
or this in App Delegate
[[UITabBar appearance] setBackgroundColor:[UIColor blackColor]];
for changing color of unselect icons of tabbar
For iOS 10:
// this code need to be placed on home page of tabbar
for(UITabBarItem *item in self.tabBarController.tabBar.items) {
item.image = [item.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
Above iOS 10:
// this need to be in appdelegate didFinishLaunchingWithOptions
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor blackColor]];
There are some good ideas in the existing answers, many work slightly differently and what you choose will also depend on which devices you target and what kind of look you're aiming to achieve. UITabBar is notoriously unintuitive when it come to customizing its appearance, but here are a few more tricks that may help:
1). If you're looking to get rid of the glossy overlay for a more flat look do:
tabBar.backgroundColor = [UIColor darkGrayColor]; // this will be your background
[tabBar.subviews[0] removeFromSuperview]; // this gets rid of gloss
2). To set custom images to the tabBar buttons do something like:
for (UITabBarItem *item in tabBar.items){
[item setFinishedSelectedImage:selected withFinishedUnselectedImage:unselected];
[item setImageInsets:UIEdgeInsetsMake(6, 0, -6, 0)];
}
Where selected and unselected are UIImage objects of your choice. If you'd like them to be a flat colour, the simplest solution I found is to create a UIView with the desired backgroundColor and then just render it into a UIImage with the help of QuartzCore. I use the following method in a category on UIView to get a UIImage with the view's contents:
- (UIImage *)getImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [[UIScreen mainScreen]scale]);
[[self layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
3) Finally, you may want to customize the styling of the buttons' titles. Do:
for (UITabBarItem *item in tabBar.items){
[item setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor redColor], UITextAttributeTextColor,
[UIColor whiteColor], UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
[UIFont boldSystemFontOfSize:18], UITextAttributeFont,
nil] forState:UIControlStateNormal];
}
This lets you do some adjustments, but still quite limited. Particularly, you cannot freely modify where the text is placed within the button, and cannot have different colours for selected/unselected buttons. If you want to do more specific text layout, just set UITextAttributeTextColor to be clear and add your text into the selected and unselected images from part (2).
[v setBackgroundColor ColorwithRed: Green: Blue: ];
Another solution (which is a hack) is to set the alpha on the tabBarController to 0.01 so that it is virtually invisible yet still clickable. Then set a an ImageView control on the bottom of the MainWindow nib with your custom tabbar image underneath the alpha'ed tabBarCOntroller. Then swap the images, change colors or hightlight when the tabbarcontroller switches views.
However, you lose the '...more' and customize functionality.
Hi There am using iOS SDK 4 and i was able to solve this issue with just two lines of code and it's goes like this
tBar.backgroundColor = [UIColor clearColor];
tBar.backgroundImage = [UIImage imageNamed:#"your-png-image.png"];
Hope this helps!
if ([tabBar respondsToSelector:#selector(setBackgroundImage:)]) {
// ios 5 code here
[tabBar setBackgroundImage:[UIImage imageNamed:#"image.png"]];
}
else {
// ios 4 code here
CGRect frame = CGRectMake(0, 0, 480, 49);
UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
UIImage *tabbag_image = [UIImage imageNamed:#"image.png"];
UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
tabbg_view.backgroundColor = tabbg_color;
[tabBar insertSubview:tabbg_view atIndex:0];
}
Swift 3.0 answer: (from Vaibhav Gaikwad)
For changing color of unselect icons of tabbar:
if #available(iOS 10.0, *) {
UITabBar.appearance().unselectedItemTintColor = UIColor.white
} else {
// Fallback on earlier versions
for item in self.tabBar.items! {
item.image = item.image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}
}
For changing text color only:
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red, for: .selected)
Swift 3 using appearance from your AppDelegate do the following:
UITabBar.appearance().barTintColor = your_color

Resources