How to set the title of UIToolBar? - objective-c

How can I set the title of UIToolBar such that it looks the same as the title in UINavigationBar?
I tried to use a button with plain style, it looks ok, but it will be highlighted when I click on it... Is there any better way to set the title in the detail view of split view?

This is what I use to present a title on a toolbar that will not highlight when pressed:
#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
// choose whatever width you need instead of 600
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 600, 23)];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.shadowColor = UIColorFromRGB(0xe5e7eb);
label.shadowOffset = CGSizeMake(0, 1);
label.textColor = UIColorFromRGB(0x717880);
label.text = #"your title";
label.font = [UIFont boldSystemFontOfSize:20.0];
UIBarButtonItem *toolBarTitle = [[UIBarButtonItem alloc] initWithCustomView:label];
[label release];

I think this would be much cleaner:
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:frame];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:#"Your Title"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
NSArray *items = [[NSArray alloc] initWithObjects:spacer, item, spacer, nil];
[toolbar setItems:items];
toolbar.userInteractionEnabled = NO;

This solves the highlighting problem, disabled problem, and touch problem.
Toolbar and titleButton were both created in IB.
The view title is covered by the toolbar. So put the title in a toolbar.
self.titleButton.title = #"Order"; // myInterestingTitle
It looks like this:
Disable to prevent any highlighting, and to stop it from responding to touches.
self.titleButton.enabled=NO;
Then it looks like this:
It will look disabled, so set the color for disabled to white,
which has an implicit alpha=1.0.
This effectively overrides the 'disabled' look.
[self.titleButton setTitleTextAttributes:
[NSDictionary dictionaryWithObject:[UIColor whiteColor]
forKey:UITextAttributeTextColor]
forState:UIControlStateDisabled ];
Here's what you get:

Swift 5 version of Rayfleck's great answer:
let titleButton = UIBarButtonItem(title: "My Title", style: .plain, target: nil, action: nil)
titleButton.isEnabled = false
titleButton.setTitleTextAttributes([.foregroundColor : UIColor.black], for: .disabled)
Add this button to the toolbar as normal.

Put the regular "Rounded Rect Button" (UIButton) on toolbar (not "Bar Button Item")! Be aware, that behind the scene, IB wrap UIButton with UIBarButtonItem. It is why you have to click on button twice to get to UIButton properties (true for Xcode 4.2).
Get to UIButton properties. When you click first time, you will get "Bar button item" properties (it is what IB created automatically for you). Now click second time, you'll get to "Button" properties (also, when you selected UIButton you can't resize it and can't see resize markers).
In the Button properties set type to "Custom" to remove rounded rect border around button (you may need to resize button in IB to refresh it before you can see difference).
In the Button properties under "View" uncheck "User Interaction Enabled".

UILabel* title = [[[UILabel alloc] init] autorelease];
[title setBackgroundColor:[UIColor clearColor]];
[title setFont:[UIFont boldSystemFontOfSize:20]];
[title setTextAlignment:UITextAlignmentCenter];
[title setTextColor:[UIColor grayColor]];
[title.layer setShadowColor:[[UIColor colorWithWhite:1.0 alpha:0.5] CGColor]];
[title.layer setShadowOffset:CGSizeMake(0, 1)];
[title.layer setShadowRadius:0.0];
[title.layer setShadowOpacity:1.0];
[title.layer setMasksToBounds:NO];
[title setText:#"Sample Title"];
[title sizeToFit];
// [[[UIBarButtonItem alloc] initWithCustomView:title] autorelease]

Use a UIBarButtonItem in the plain style and additionally cover the toolbar in the appropriate area with a UIView that has a clear background. The view consumes the taps and hides them from the bar button item. Make sure you set the autoresizing mask correctly.

You can uncheck "Shows touch on Highlight" in Interface Builder.

Related

Toolbar button unresponsive after iOS 13.4.1 update

I have had a medical calculation app for cardiac ultrasound in the App Store since 2011. At the bottom of each data entry screen is a toolbar with buttons to analyze all data, designate the open calculation as a favorite, and clear all active data from all calculations. After the most recent iOS update to 13.4.1, the Clear button at the bottom right of the screen has become unresponsive. If I put the app in the background, open another app, and then switch back to my app, then the Clear button becomes responsive again. If I move the Clear button to the left side of the toolbar, next to the Analyze button, then it functions without a problem. Since the code that displays these buttons has been the same for years and multiple iOS versions, I am wondering if possibly there is a bug in iOS 13.4.1 causing this issue.
Here is the code used to generate the toolbar:
//Initialize the toolbar
toolbar = [[UIToolbar alloc] init];
toolbar.barStyle = UIBarStyleDefault;
//Set the toolbar to fit the width of the app.
[toolbar sizeToFit];
//Caclulate the height of the toolbar
CGFloat toolbarHeight = [toolbar frame].size.height;
//Get the bounds of the parent view
CGRect rootViewBounds = self.parentViewController.view.bounds;
//Get the height of the parent view.
CGFloat rootViewHeight = CGRectGetHeight(rootViewBounds);
//Get the width of the parent view,
CGFloat rootViewWidth = CGRectGetWidth(rootViewBounds);
//Create a rectangle for the toolbar
CGRect rectArea = CGRectMake(0, rootViewHeight - toolbarHeight - [sharedVariableState g_toolbar_adjuster_for_Home_indicator], rootViewWidth, toolbarHeight);
//Reposition and resize the receiver
[toolbar setFrame:rectArea];
//Create two buttons separated by spacer item.
UIBarButtonItem *analyzeButton = [[UIBarButtonItem alloc] initWithTitle:#"Analyze" style:UIBarButtonItemStylePlain target:self action:#selector(analyze_clicked:)];
UIBarButtonItem *clearButton = [[UIBarButtonItem alloc] initWithTitle:#"Clear" style:UIBarButtonItemStylePlain target:self action:#selector(clear_clicked:)];
//Use this to put space in between your toolbox buttons
UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; //Load NSUserDefaults.
NSMutableArray *objectArrayMutable = [[NSMutableArray alloc]init];
objectArrayMutable = [[prefs objectForKey:#"savedFavoritesArray"] mutableCopy];
int favoriteChosenAlready = 0;
if ([objectArrayMutable count] > 0) {
for (int arrayCounter = 0; arrayCounter < [objectArrayMutable count]; arrayCounter++) {
if ([[objectArrayMutable objectAtIndex:arrayCounter] integerValue] == 58) {
favoriteChosenAlready = 1;
}
}
}
UIButton *favButton = [[UIButton alloc] init];
if (favoriteChosenAlready == 0) {
//Display empty star.
[favButton setImage:[UIImage imageNamed:#"Star_button_empty.png"] forState:UIControlStateNormal];
}
else {
//Display filled star.
[favButton setImage:[UIImage imageNamed:#"Star_button_filled.png"] forState:UIControlStateNormal];
}
[favButton addTarget:self action:#selector(favorite_clicked:) forControlEvents:UIControlEventTouchUpInside];
[favButton setFrame:CGRectMake(280, 25, 30, 30)];
UIBarButtonItem *favoriteButton = [[UIBarButtonItem alloc] initWithCustomView:favButton];
[[UIBarButtonItem appearance] setTintColor:[UIColor lightGrayColor]]; //Make toolbar button text lightGrayColor.
[toolbar setItems:[NSArray arrayWithObjects:analyzeButton,flexItem,favoriteButton,flexItem,clearButton,nil]];
//Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];
To clarify, the Clear button here now is unresponsive:
[toolbar setItems:[NSArray arrayWithObjects:analyzeButton,flexItem,favoriteButton,flexItem,clearButton,nil]];
However, just rearranging the sequence of buttons in the toolbar fixes the problem:
[toolbar setItems:[NSArray arrayWithObjects:analyzeButton,clearButton,favoriteButton,flexItem,flexItem,nil]];

navigation menu not at full width of screen

I'm writing an app in objective C for ios 8, and my navigation bar has an annoying margin thats causing it to be shifted to the right ~20 pixels for leftBarButtonItem and ~20 left for rightBarButtonItem, as shown in the image below. I have tried using negative spacers per some other posts to no avail. Any ideas?
(I'm trying to do this without using storyboards or xibs.)
Here is the code:
UIToolbar* toolbar_temp = [[UIToolbar alloc] init];
toolbar_temp.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 45);
toolbar_temp.barTintColor= [UIColor blackColor];
NSMutableArray *items = [[NSMutableArray alloc] init];
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIImage *camimage = [UIImage imageNamed:#"cancel"];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithImage:camimage style:UIBarButtonItemStylePlain target:self action:nil];
[items addObject:spaceItem ];
[items addObject:customItem ];
[items addObject:spaceItem ];
[toolbar_temp setItems:items animated:NO];
UIBarButtonItem *allButton = [[UIBarButtonItem alloc] initWithCustomView:toolbar_temp];
self.navigationItem.leftBarButtonItem = allButton;
EDIT:
I'm not sure if this gives any hints, but for some reason this works:
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlackTranslucent];
While this does not:
[self.navigationController.navigationBar setBarStyle:UIBarStyleBlackTranslucent];
SOLUTION:
I ended up finding the solution myself. The issue was that I have a tabbar controller which had a navigation controller as one of the views. The navigation controller can only be setup in viewDidload, which doesn't get called in tabbar controllers. The solution was to add viewDidAppear and add the navigation controller within that function.
- (void)viewDidAppear:(BOOL)animated{[self addToolbar];}
Thanks all for the help!
It seems you cannot alter the minimum margins. You can do is add the toolbar_temp to the navigation bar:
[self.navigationController.navigationBar addSubview:toolbar_temp];
Or add to the self.view:
self.navigationController.navigationBarHidden = YES;
[self.view addSubview:toolbar_temp];

UINavigationBar setTitleTextAttributes

I'm trying to change the color of NavigationBars title while I'm on a viewcontroller (not before pushing it). by using:
[[[self navigationController] navigationBar] setTitleTextAttributes:textAttributes];
But this line of code only works before pushes or pops. I was wondering if there is a way to force this without navigating?
I would say the simplest way is to create an UILabel with the same style you want for the UINavigationController title and set the label to the navigationItem.titleView.
Try this one
UILabel * label = [[[UILabel alloc] initWithFrame:CGRectMake(0,0,45,45)] autorelease];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.text = self.navigationItem.title;
self.navigationItem.titleView = label;
create custom label and set it as titleView of your navigation bar

Adding two buttons to rightBarButtonItems not working

I am not sure why the following code is not working:
UIBarButtonItem *newButton = [[UIBarButtonItem alloc] initWithTitle:#"New" style:UIBarButtonItemStyleBordered target:self action:#selector(newClicked:)];
UIBarButtonItem *shareButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(share:)];
self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:newButton, shareButton, nil];
It only display the "newButton" UIBarButtonItem on the navigation bar and not the "shareButton" button.
I found a different issue involving this behavior.
If you've set a custom titleView (navigationItem.titleView = ...) then the navigation item can sometimes hide your buttons except the first one if it doesn't have room.
So make sure you limit the width of your custom titleView.
rightBarButtonItems is in ios 5.
I think the issue is with the objet name new, please change this to any other name like newButton or something like that.
Because new is a keyword used for memory allocation in C++
Looks like the problem had to do with code following the questioned code:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 400, 44)];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:#"Marker Felt" size:26.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor =[UIColor whiteColor];
label.text=self.title;
self.navigationItem.titleView = label;
[label release];
Posting this now in case someone else encounters this problem!

spacing rightBarButtonItems in UINavigationBar

i am using the rightBarButtonItems property of UINavigationBar to add two buttons on the right part of my navigation bar. is it possible to make the spacing between these two buttons wider?
thanks
You can add an UIBarButtonSystemItemFlexibleSpace item between your two buttons.
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
I was not able to get the flexible space to work in my situation but here is the code I used to be able to position the rightBarButtonItem: Note, I put a border around the UIView so you can see what it looks like with having the image in there.
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(89,40,100,30)];
containerView.layer.borderColor = [[UIColor redColor] CGColor];
containerView.layer.borderWidth = 1.0;
UIImage *image = [UIImage imageNamed:#"nav-icon.png"];
UIButton *navigationButton = [UIButton buttonWithType:UIButtonTypeCustom];
[navigationButton setFrame:CGRectMake(67,0,25,25)];
[navigationButton setImage:image forState:UIControlStateNormal];
[containerView addSubview:navigationButton];
UIBarButtonItem *navigationBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:containerView];
self.navigationItem.rightBarButtonItem = navigationBarButtonItem;