Colour changed in iOS7.1, how to change searchBar colour? - ios

On iOS7.0.3 - 7.0.6, my searchBar colour is Gold/yellow colour like this:
But on iOS 7.1, colour becomes like this:
I set
searchBar.tintColor = [UIColor clearColor];
searchBar.backgroundColor = goldColor;
searchBar.tintColor = [UIColor blackColor];
I've tried so many ways and all are failed. Can anyone figure out what changes in iOS 7.1?
============== My fix ===============
I fix this problem by covering a view on searchBar and add the search text filed as subview on this new view.
I need point out that the gold status bar is a subView of searchBar, and it's frame is CGRectMake(0, -20, 320, 20) and it's background colour is gold.
At first, I set this:
_searchBar.translucent = YES;
_searchBar.scopeBarBackgroundImage = [self imageWithColor:UWGold];
and looks like this:
Then, I expand the view cover the status bar, I changed the view's frame.size.height + searchBar's height, then use this line:
UITextField *textSearchField = [_searchBar valueForKey:#"_searchField"];
to get the textSearchField, then add this textSearchField to the cover view.
At last, the searchBar is exactly like when on iOS 7.0
Not a good way, I need figure out what changes on iOS 7.1 and use a right way to implement this.

Try this:
if(IOS_7)
{
self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
self.searchBar.backgroundImage = [UIImage imageWithColor:[UIColor redColor] cornerRadius:5.0f];
}
Hopefully this will help you.

None of the above answers worked for me on iOS 7/8. Here's some setup code that did the trick:
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 44)];
searchBar.scopeButtonTitles = #[#"Scope1", #"Scope2"];
searchBar.selectedScopeButtonIndex = 0;
searchBar.backgroundColor = [UIColor clearColor];
searchBar.barTintColor = [UIColor clearColor];
searchBar.translucent = YES; // SUPER IMPORTANT, REMOVING THIS MESSED UP THE SCOPE BAR
// ONLY USE IMAGES, NOT BACKGROUND COLORS
UIImage *searchBarBackgroundImage = [[UIImage imageNamed:#"SearchBarBackgroundImage"];
UIImage *scopeBarBackgroundImage = [[UIImage imageNamed:#"ScopeBarBackgroundImage"];
[searchBar setBackgroundImage:searchBarBackgroundImage
forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefault];
searchBar.scopeBarBackgroundImage = scopeBarBackgroundImage;
searchBar.tintColor = [UIColor whiteColor];

I used next approach for changing backgroundColor of searchBar
1.As suggested by #Ben Jackson - set BackgroundImage
[self.searchBar setBackgroundImage:[self imageWithColor:[UIColor blueColor]] forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefault];
2.Change textField to what u need according to design
NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];
for( int i = 0; i < searchBarSubViews.count; i++) {
if([[searchBarSubViews objectAtIndex:i] isKindOfClass:[UITextField class]]) {
UITextField *searchTextField = (UITextField *)[searchBarSubViews objectAtIndex:i];
[searchTextField setTintColor:[UIColor blueColor]];
searchTextField.placeholder = #"Search";
searchTextField.backgroundColor = [UIColor whiteColor];
searchTextField.layer.borderColor = [UIColor blueColor].CGColor;
searchTextField.layer.borderWidth = 1.0f;
searchTextField.layer.cornerRadius = 8.0f;
searchTextField.leftViewMode = UITextFieldViewModeNever;
}
}
Also method for image from color - here
Result:

Related

Remove between UITableView and UINavigationBar

I have an UITableView which I am trying to make the background color of the first cell match the color of the UINavigationBar, as seen in the screenshot below.
However, as you can see, there is a dark border between both objects which I don't know where is coming from.
Moreover, it is evident that the tone of the color used is not the same in both cases, despite using the same [UIColor colorWithRed:] code. This is not the main problem, but I wanted to mention this too.
Any thoughts?
EDIT
viewDidLoad:
self.tableView.separatorColor = [UIColor clearColor];
self.tableView.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.0];
self.tableView.scrollEnabled = NO;
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.clipsToBounds = YES;
self.navigationController.navigationBar.translucent = NO;
cellForRowAtIndexPath:
cell.backgroundColor = myColor;
Try this:
[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
But if you want to remove the hairline alone and keeping the blur effect, try:
self.navigationController.navigationBar.clipsToBounds = YES;
and by the way, this is my actual code of testing:
- (void)viewDidLoad
{
[super viewDidLoad];
UIView *red = [[UIView alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
red.backgroundColor = [UIColor redColor];
[self.view addSubview:red];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.navigationBar.clipsToBounds = YES;
}
Sample output be:
Update:
Looks like -clipToBounds do not suits your implementation.
Here what i think suits yours:
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 green:0.5 blue:0.97 alpha:1.0];
[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.translucent = NO;
Before: After:
Note: The [UIColor colorWithRed:0 green:0.5 blue:0.97 alpha:1.0] is just for example, assign your desired color to .barTintColor.
Perhaps
//0084D3
UIColor * color = [UIColor colorWithRed:0/255.0f green:132/255.0f blue:211/255.0f alpha:1.0f];
//006FCC
UIColor * color = [UIColor colorWithRed:0/255.0f green:111/255.0f blue:204/255.0f alpha:1.0f];
is what you need based from UIColor Code Generator :)
Hope this is helpful.. Cheers.. :)
The line you're seeing is the navigation bar's shadowImage. You can remove it by adding
self.navigationController.navigationBar.shadowImage = [UIImage new];
EDIT
Not sure if you've solved this already, but I set up a brand new project with a UITableViewController embedded in a UINavigationController and there's no line under the nav bar. Here's the configuration I did:
In viewDidLoad:
self.navigationController.navigationBar.translucent = NO;
[self.navigationController.navigationBar setBarTintColor:myColor];
self.tableView.backgroundColor = myColor;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
In tableView:cellForRowAtIndexPath:
cell.contentView.backgroundColor = myColor;
cell.textLabel.backgroundColor = myColor;
cell.textLabel.text = #"this";
Nothing special in Storyboard.

Cannot change searchbar text color, but I am able to change background color

I have a searchbar embedded in a navigationbar. I'm able to change background color, but for the life of me cannot change text color. I have the following code in my viewdidload. What is missing to get the text to change?
if(!itemSearchBar)
{
itemSearchBar = [[UISearchBar alloc] init];
[itemSearchBar setFrame:CGRectMake(0, 0, self.view.frame.size.width, 55)];
itemSearchBar.placeholder = #"What are you looking for?";
itemSearchBar.delegate = self;
UITextField *txfSearchField = [itemSearchBar valueForKey:#"_searchField"];
txfSearchField.backgroundColor = [UIColor colorWithRed:130/255.0 green:58/255.0 blue:23/255.0 alpha:1.0];
UISearchDisplayController *searchCon = [[UISearchDisplayController alloc]
initWithSearchBar:itemSearchBar
contentsController:self ];
[searchCon setActive:NO animated:YES];
self.searchDisplayController = searchCon;
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
self.searchDisplayController.displaysSearchBarInNavigationBar=YES;
I've read that the following should work but doesn't:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];
I've also tried:
itemSearchBar.tintColor = [UIColor redColor];
txfSearchField.textColor = [UIColor redColor];
Any suggestions???
I think you are looking at the color of placeholder text and not typing anything in the textfield. Otherwise, your code seems correct. The method
txfSearchField.textColor = [UIColor redColor]
must work. Type anything in the field and you will see red color.

removing uinavigationbar title margins

I modified my navigation bar as follows in app delegate:
NSDictionary *settings = #{
UITextAttributeFont : [UIFont fontWithName:#"impact" size:36.0],
UITextAttributeTextColor : [UIColor whiteColor],
UITextAttributeTextShadowColor : [UIColor clearColor],
UITextAttributeTextShadowOffset : [NSValue valueWithUIOffset:UIOffsetZero]};
[[UINavigationBar appearance] setTitleTextAttributes:settings];
But the font cuts down like this for the larger font. :
I tried doing this in viewWillAppear of my VC, :
UIView *newTitleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[newTitleView setBackgroundColor:[UIColor blackColor]];
[self.navigationController.navigationBar addSubview:newTitleView];
Then I was going to align title to center. But that just doesn't seems right. Only thing I actually need is to remove margins at top and bottom of the title Label. How do I go about it.
Try this code and don't set setTitleTextAttributes
UILabel *titleView = (UILabel *)self.navigationItem.titleView;
if (!titleView) {
titleView = [[UILabel alloc] initWithFrame:CGRectZero];
titleView.backgroundColor = [UIColor clearColor];
titleView.font = [UIFont boldSystemFontOfSize:20.0];
titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleView.textColor = [UIColor yellowColor]; // Change to desired color
self.navigationController.navigationItem.titleView = titleView;
[titleView release];
}
titleView.text = title;
[titleView sizeToFit];
Well the easiest way i would suggest is to use a UIView with label and button customised for the requirement and use it,not on navigation bar.
mnavigation bar height customization is the trouble that the height is fixed and the subview also it may affect .So I suggest to go with a custom header view subclassed with UIView
You can subclass to the UILabel and override drawTextInRect: like this:
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = {0, 5, 0, 5};
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
For more useful link you can find
here

Why does navigationItem.titleView align left when presentmodalviewcontroller called?

I'm using a UILabel for the titleView of a navigation bar (I'm making simple in-app web browser). It works fine, except that when I present a modal view controller, the titleView shifts from the center of the navbar to the far left (underneath the back button). I've tested in 3.0 and up. Here is relevant code:
- (void)viewDidLoad {
[super viewDidLoad];
// Title view label
CGRect labelFrame = CGRectMake(0.0, 0.0, 120.0, 36.0);
UILabel *label = [[[UILabel alloc] initWithFrame:labelFrame] autorelease];
label.font = [UIFont boldSystemFontOfSize:14];
label.numberOfLines = 2;
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.shadowColor = [UIColor blackColor];
label.shadowOffset = CGSizeMake(0.0, -1.0);
label.lineBreakMode = UILineBreakModeMiddleTruncation;
self.navigationItem.titleView = label;
}
-(void)displayComposerSheet:(NSString*)mailto
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[self presentModalViewController:picker animated:YES];
[picker release];
}
Screenshots:
Any idea why this is happening? Thanks.
I looked into the problem with some hit and try and found the following facts:
If the UINavigationBar doesn't have the rightBarButtonItem, the titleView shifts towards the right by ~30pts.
It could be reproduced for leftBarButtonItem. But I haven't tried.
In a scenario where the a default UINavigationBar's (with no changes to rightBarButtonItem defaults) titleView is set. And then a new UIView is pushed to the navigation stack which HAS a rightBarButtonItem. Now, if this view is popped [with back button], the navigation bar will remove the rightBarButtonItem. And this will account for the weird offset that shifts the titleView towards a side.
How I fixed the problem was like this:
self.navigationItem.titleView = myCustomTitleView;
// Fake right button to align titleView properly.
UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 1)]];
// Width equivalent to system default Done button's (which appears on pushed view in my case).
rightBarButtonItem.enabled = NO;
self.navigationItem.rightBarButtonItem = rightBarButtonItem;
Everything is sweet now. yummmm.
Thanks to DougW for pointing me in right direction. Here's the best hack I found. Basically I retain the UILabel as a class property. Before presenting modal view I unset the titleView, and then reset it immediately after. When the modal view is dismissed I unset then reset the titleView. To the user none of this is visibly notable.
-(void)displayComposerSheet:(NSString*)mailto
{
self.navigationItem.titleView = nil;
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
picker.navigationBar.tintColor = [APPDELEGATE getNavTintColor];
[picker setToRecipients:[NSArray arrayWithObject:mailto]];
[self presentModalViewController:picker animated:YES];
[picker release];
self.navigationItem.titleView = titlelabel;
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
self.navigationItem.titleView = nil;
self.navigationItem.titleView = titlelabel;
[self dismissModalViewControllerAnimated:YES];
}
Does it animate? It may be animating the title view as though it's transitioning to a new view. I don't see anything wrong with your code as written.
I would suggest in your displayComposerSheet, you just unset the titleView, or animate the alpha of the titleView to 0.0. Then, animate it back to 1.0 when you dismiss the modal view controller. Not ideal, but it may look better that way.
Frankly, the whole UINavigation system is crap. We went ahead and re-wrote it ground up because of bizarre issues like these.
The only problem is your frame size. so u have to change it.
Try this one.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 36.0)];
label.font = [UIFont boldSystemFontOfSize:14];
label.numberOfLines = 2;
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.shadowColor = [UIColor blackColor];
label.shadowOffset = CGSizeMake(0.0, -1.0);
label.lineBreakMode = UILineBreakModeMiddleTruncation;
label.text=#"Stack Overflow";
self.navigationItem.titleView = label;
You can try move the code in viewDidAppear:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// You code to customize title view
self.navigationItem.titleView = logoImage;
}
It works for me.
If you change the width size to be small like 100 points or smaller instead of 120 you set, this problem may go away. Setting width of the label smaller worked for me.
UIView *view= [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[view setUserInteractionEnabled:NO];
view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"logo_small.png"]];
UIBarButtonItem *barButton=[[UIBarButtonItem alloc]initWithCustomView:view ];
self.navigationItem.leftBarButtonItem = barButton;

iPhone Navigation Bar Title text color

It seems the iOS Navigation Bar title color is white by default. Is there a way to change it to a different color?
I am aware of the navigationItem.titleView approach using an image. Since my design skills are limited and I failed to get the standard glossy, I prefer changing the text color.
Any insight would be much appreciated.
Modern approach
The modern way, for the entire navigation controller… do this once, when your navigation controller's root view is loaded.
[self.navigationController.navigationBar setTitleTextAttributes:
#{NSForegroundColorAttributeName:[UIColor yellowColor]}];
However, this doesn't seem have an effect in subsequent views.
Classic approach
The old way, per view controller (these constants are for iOS 6, but if want to do it per view controller on iOS 7 appearance you'll want the same approach but with different constants):
You need to use a UILabel as the titleView of the navigationItem.
The label should:
Have a clear background color (label.backgroundColor = [UIColor clearColor]).
Use bold 20pt system font (label.font = [UIFont boldSystemFontOfSize: 20.0f]).
Have a shadow of black with 50% alpha (label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]).
You'll want to set the text alignment to centered as well (label.textAlignment = NSTextAlignmentCenter (UITextAlignmentCenter for older SDKs).
Set the label text color to be whatever custom color you'd like. You do want a color that doesn't cause the text to blend into shadow, which would be difficult to read.
I worked this out through trial and error, but the values I came up with are ultimately too simple for them not to be what Apple picked. :)
If you want to verify this, drop this code into initWithNibName:bundle: in PageThreeViewController.m of Apple's NavBar sample. This will replace the text with a yellow label. This should be indistinguishable from the original produced by Apple's code, except for the color.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// this will appear as the title in the navigation bar
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = NSTextAlignmentCenter;
// ^-Use UITextAlignmentCenter for older SDKs.
label.textColor = [UIColor yellowColor]; // change this color
self.navigationItem.titleView = label;
label.text = NSLocalizedString(#"PageThreeTitle", #"");
[label sizeToFit];
}
return self;
}
Edit: Also, read Erik B's answer below. My code shows the effect, but his code offers a simpler way to drop this into place on an existing view controller.
I know this is a pretty old thread, but I think it would be useful to know for new users that iOS 5 brings a new property for establishing title properties.
You can use UINavigationBar's setTitleTextAttributes for setting the font, color, offset, and shadow color.
In addition you can set the same default UINavigationBar's Title Text Attributes for all the UINavigationBars throughout your application.
For example like so:
NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor],UITextAttributeTextColor,
[UIColor blackColor], UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(-1, 0)], UITextAttributeTextShadowOffset, nil];
[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
In iOS 5 you can change the navigationBar title color in this manner:
navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName: [UIColor yellowColor]};
Based on Steven Fisher's answer I wrote this piece of code:
- (void)setTitle:(NSString *)title
{
[super setTitle:title];
UILabel *titleView = (UILabel *)self.navigationItem.titleView;
if (!titleView) {
titleView = [[UILabel alloc] initWithFrame:CGRectZero];
titleView.backgroundColor = [UIColor clearColor];
titleView.font = [UIFont boldSystemFontOfSize:20.0];
titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleView.textColor = [UIColor yellowColor]; // Change to desired color
self.navigationItem.titleView = titleView;
[titleView release];
}
titleView.text = title;
[titleView sizeToFit];
}
The advantage of this code, besides dealing with the frame properly, is that if you change the title of your controller the custom title view will also get updated. No need to update it manually.
Another big advantage is that it makes it really simple to enable custom title color. All you need to do is to add this method to the controller.
Most of the above suggestions are deprecated now, for iOS 7 use -
NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor],NSForegroundColorAttributeName,
[UIColor whiteColor],NSBackgroundColorAttributeName,nil];
self.navigationController.navigationBar.titleTextAttributes = textAttributes;
self.title = #"Title of the Page";
Also, checkout the NSAttributedString.h for various text properties that could be set.
In IOS 7 and 8, you can change the Title's color to let's say green
self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor greenColor] forKey:NSForegroundColorAttributeName];
To keep the question up-to-date, I'll add Alex R. R. solution, but in Swift:
self.navigationController.navigationBar.barTintColor = .blueColor()
self.navigationController.navigationBar.tintColor = .whiteColor()
self.navigationController.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.whiteColor()
]
Which results to:
Swift Version
I found most of you guys presented the answers of Objective_C version
I would like to implement this function by using Swift for anyone who needs it.
In ViewDidload
1.To make NavigationBar background becomes color (for example: BLUE)
self.navigationController?.navigationBar.barTintColor = UIColor.blueColor()
2.To make NavigationBar background becomes Image (for example : ABC.png)
let barMetrix = UIBarMetrics(rawValue: 0)!
self.navigationController?.navigationBar
.setBackgroundImage(UIImage(named: "ABC"), forBarMetrics: barMetrix)
3.To change NavigationBar title (for example :[Font:Futura,10] [Color:Red])
navigationController?.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.redColor(),
NSFontAttributeName : UIFont(name: "Futura", size: 10)!
]
(hint1: don't forget the "!" mark after the UIFont)
(hint2: there are lots of attributes of the title text, command click
the "NSFontAttributeName" you can enter the class and view keyNames
and the Objects types they required)
I hope I can help!:D
Method 1, set it in IB:
Method 2, one line of code:
navigationController?.navigationBar.barTintColor = UIColor.blackColor()
The solution by tewha works well if you are trying to change the color on a page, but I want to be able to change the color on every page. I made some small modifications so that it would work for all pages on a UINavigationController
NavigationDelegate.h
//This will change the color of the navigation bar
#import <Foundation/Foundation.h>
#interface NavigationDelegate : NSObject<UINavigationControllerDelegate> {
}
#end
NavigationDelegate.m
#import "NavigationDelegate.h"
#implementation NavigationDelegate
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
CGRect frame = CGRectMake(0, 0, 200, 44);//TODO: Can we get the size of the text?
UILabel* label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor yellowColor];
//The two lines below are the only ones that have changed
label.text=viewController.title;
viewController.navigationItem.titleView = label;
}
#end
From iOS 5 onwards we have to set title text color and font of navigation bar using titleTextAttribute Dictionary(predefined dictionary in UInavigation controller class reference).
[[UINavigationBar appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor blackColor],UITextAttributeTextColor,
[UIFont fontWithName:#"ArialMT" size:16.0], UITextAttributeFont,nil]];
Short and sweet.
[[[self navigationController] navigationBar] setTitleTextAttributes:#{NSForegroundColorAttributeName: [UIColor redColor]}];
Use the code below in any view controller viewDidLoad or viewWillAppear method.
- (void)viewDidLoad
{
[super viewDidLoad];
//I am using UIColor yellowColor for an example but you can use whatever color you like
self.navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName: [UIColor yellowColor]};
//change the title here to whatever you like
self.title = #"Home";
// Do any additional setup after loading the view.
}
This is my solution based upon Stevens
Only real difference is I put some handling in for adjust the position if depending on the text length, seems to be similar to how apple do it
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft), 0, 480,44)];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.font = [UIFont boldSystemFontOfSize: 20.0f];
titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleLabel.textAlignment = ([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft);
titleLabel.textColor = [UIColor redColor];
titleLabel.text = self.title;
self.navigationItem.titleView = titleLabel;
[titleLabel release];
You may want to adjust the 10 value depending on your font size
Swift 4 & 4.2 version:
self.navigationController.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
I ran into the problem with my nav buttons throwing the text out of center (when you only have one button). To fix that I just changed my frame size like so:
CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
I've customized the navigationBar's background image and left button item, and the gray title not fit the background. Then I use:
[self.navigationBar setTintColor:[UIColor darkGrayColor]];
to change the tint color to gray. And the title is white now! That's what I want.
Hope to help also :)
It's recommended to set self.title as this is used while pushing child navbars or showing title on tabbars.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// create and customize title view
self.title = NSLocalizedString(#"My Custom Title", #"");
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
titleLabel.text = self.title;
titleLabel.font = [UIFont boldSystemFontOfSize:16];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor whiteColor];
[titleLabel sizeToFit];
self.navigationItem.titleView = titleLabel;
[titleLabel release];
}
}
This is a pretty old thread but I think of providing answer for setting Color, Size and Vertical Position of Navigation Bar Title for iOS 7 and above
For Color and Size
NSDictionary *titleAttributes =#{
NSFontAttributeName :[UIFont fontWithName:#"Helvetica-Bold" size:14.0],
NSForegroundColorAttributeName : [UIColor whiteColor]
};
For Vertical Position
[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:-10.0 forBarMetrics:UIBarMetricsDefault];
Set Title and assign the attributes dictionary
[[self navigationItem] setTitle:#"CLUBHOUSE"];
self.navigationController.navigationBar.titleTextAttributes = titleAttributes;
This works for me in Swift:
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
self.navigationItem.title=#"Extras";
[self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:#"HelveticaNeue" size:21], NSFontAttributeName,[UIColor whiteColor],UITextAttributeTextColor,nil]];
Use like this for Orientation support
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)];
[view setBackgroundColor:[UIColor clearColor]];
[view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];
UILabel *nameLabel = [[UILabel alloc] init];
[nameLabel setFrame:CGRectMake(0, 0, 320, 40)];
[nameLabel setBackgroundColor:[UIColor clearColor]];
[nameLabel setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin];
[nameLabel setTextColor:[UIColor whiteColor]];
[nameLabel setFont:[UIFont boldSystemFontOfSize:17]];
[nameLabel setText:titleString];
[nameLabel setTextAlignment:UITextAlignmentCenter];
[view addSubview:nameLabel];
[nameLabel release];
self.navigationItem.titleView = view;
[view release];
to set font size of title i have used following conditions.. maybe helpfull to anybody
if ([currentTitle length]>24) msize = 10.0f;
else if ([currentTitle length]>16) msize = 14.0f;
else if ([currentTitle length]>12) msize = 18.0f;
An update to Alex R. R.'s post using the new iOS 7 text attributes and modern objective c for less noise:
NSShadow *titleShadow = [[NSShadow alloc] init];
titleShadow.shadowColor = [UIColor blackColor];
titleShadow.shadowOffset = CGSizeMake(-1, 0);
NSDictionary *navbarTitleTextAttributes = #{NSForegroundColorAttributeName:[UIColor whiteColor],
NSShadowAttributeName:titleShadow};
[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
I do believe proper way to set the colour of UINavigationBar is:
NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor, nil];
self.titleTextAttributes = attributes;
Code above is written is subclass on UINavigationBar, obviously works without subclassing as well.
This is one of those things that are missing. Your best bet is to create your own custom Navigation Bar, add a text box, and manipulate the color that way.
After encountering the same problem (as others) of the label that moves when we insert a button in the navBar (in my case i have a spinner that i replace with a button when the date is loaded), the above solutions didn't work for me, so here is what worked and kept the label at the same place all the time:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// this will appear as the title in the navigation bar
//CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
CGRect frame = CGRectMake(0, 0, 180, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor yellowColor];
self.navigationItem.titleView = label;
label.text = NSLocalizedString(#"Latest Questions", #"");
[label sizeToFit];
}
return self;
You should call [label sizeToFit]; after setting the text to prevent strange offsets when the label is automatically repositioned in the title view when other buttons occupy the nav bar.
Can use this method in appdelegate file and can use at every view
+(UILabel *) navigationTitleLable:(NSString *)title
{
CGRect frame = CGRectMake(0, 0, 165, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = NAVIGATION_TITLE_LABLE_SIZE;
label.shadowColor = [UIColor whiteColor];
label.numberOfLines = 2;
label.lineBreakMode = UILineBreakModeTailTruncation;
label.textAlignment = UITextAlignmentCenter;
[label setShadowOffset:CGSizeMake(0,1)];
label.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
//label.text = NSLocalizedString(title, #"");
return label;
}
titleTextAttributes
Display attributes for the bar’s title text.
#property(nonatomic, copy) NSDictionary *titleTextAttributes
Discussion
You can specify the font, text color, text shadow color, and text shadow offset for the title in the text attributes dictionary, using the text attribute keys described in NSString UIKit Additions Reference.
Availability
Available in iOS 5.0 and later.
Declared In
UINavigationBar.h

Resources