after going through the questions related to UINavigationController item i came to post my exact problem ..
firstly i am not add a UINavigationController in MainWindow.xib i created and adding UINavigationController in AppDelegate file
after that in a UIViewController (not in rootViewController) class I have to add a rightbarbutton of Done type I am
adding it in a searchbarDelegate Method showing as bold:-
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
//This method is called again when the user clicks back from teh detail view.
//So the overlay is displayed on the results, which is something we do not want to happen.
if(exhibDataObj.searching)
return;
//Add the overlay view.
if(ovController == nil)
ovController = [[OverlayViewController alloc] initWithNibName:#"OverlayView" bundle:[NSBundle mainBundle]];
CGFloat yaxis = self.navigationController.navigationBar.frame.size.height;
CGFloat width = self.view.frame.size.width;
CGFloat height = self.view.frame.size.height;
//Parameters x = origion on x-axis, y = origon on y-axis.
CGRect frame = CGRectMake(0, yaxis, width, height);
ovController.view.frame = frame;
ovController.view.backgroundColor = [UIColor grayColor];
ovController.view.alpha = 0.5;
ovController.rvController = self;
[self.theTableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
exhibDataObj.searching = true;
letUserSelectRow = NO;
self.theTableView.scrollEnabled = NO;
//Add the done button.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(doneSearching_Clicked:)];
}
but this never works .
Any help will be more appreciable.
I've tested your code real quick and it seems to be working fine for me, however, I've had the same problem once back then it turned out I was setting the rightBarButtonItem to nil in my viewDidLoad method after setting it to a button. you should make sure your not making the same mistake somehow.
However if that does not work for you you can always try setting a custom button to it:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 30, 30)];
button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"done.png"]];
[button addTarget:self action:#selector(doneButtonClicked) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationController.visibleViewController.navigationItem.rightBarButtonItem = customItem;
Related
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]];
I'm trying to figure out how can I achieve something like this:
This is a toolbar and I'd like to keep the button title text without having to create the whole image with icon AND text. How can I add the icon to the left of the UIBarButtonItem while keeping the text set with:
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Button" style:UIBarButtonItemStyleBordered target:nil action:nil];
EDIT
This is what I achieved with the following code:
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"Test"] forState:UIControlStateNormal];
[customButton setTitle:#"Button" forState:UIControlStateNormal];
customButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[customButton sizeToFit];
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
Two issues here: the first is the size of the UIButton and the second is that, as you can see from the gif, the button doesn't animate properly when I tap inside the button and when I release the tap. Any ideas?
You can embed a UIButton as a custom view inside your UIBarButtonItem. You can create your UIButton however you want, including with an image and text, using -setImage:forState: and -setTitle:forState:.
UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"image"] forState:UIControlStateNormal];
[customButton setTitle:#"Button" forState:UIControlStateNormal];
[customButton sizeToFit];
UIBarButtonItem* customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
self.navigationItem.leftBarButtonItem = customBarButtonItem; // or self.navigationItem.rightBarButtonItem
Note that when doing this, you'll need to attach your IBAction methods to customButton, not to customBarButtonItem.
For more info, see the documentation for initWithCustomView:.
You can also do all of this in interface builder just by dragging a UIButton to the left bar button/right bar button slot on a navigation bar.
I was not satisfied with all solutions found on stack overflow becauseI like how UIBarButtonItenm convert images so they are displayed correctly and they can be changed with tint colour. So i discovered this solution that I can use nicely with not much code... End effect is similar to toolbar in facebook and other current apps...
When you change tint colour of view contained in UIBArButtonItem colours of image and title change accordingly, really cool , I do not have to create special images at all.
This code is called from each button like that Competition Button, and also Button is set as referencing outlet...
- (void)selectButton:(UIButton *)sender {
_competitionButton.superview.tintColor = [UIColor lightGrayColor];
_usersButton.superview.tintColor = [UIColor lightGrayColor];
_managementButton.superview.tintColor = [UIColor lightGrayColor];
sender.superview.tintColor = [UIColor whiteColor];
}
- (IBAction)onCompetitionButtonClick:(UIButton *)sender {
[self selectButton:sender];
[_scrollView scrollToPage:0 of:3];
}
In Button like that titled Competition there is only title and in bar button item there is image... This is how I have setup it and it works , maybe there are also other possibilities..
So I managed to do my solution programatically... Some users where complaining it does not work ... So how to create UTToolbar with image and item so that you can change color of button by tint and it magically alters image as well as title label ? My UI editor solution works for sure...
In this code can clarify things more and you can do it programatically either...
- (void)loadToolbar {
NSMutableArray *items = NSMutableArray.new;
[items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
for (uint pageIndex = 0; pageIndex < _controllers.count; ++pageIndex) {
UIView *itemView = [UIView.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
itemView.backgroundColor = [UIColor clearColor];
itemView.tintColor = [UIColor orangeColor];
[itemView addSubview:[self createToolbarForItemView:pageIndex]];
[itemView addSubview:[self createButtonForItemView:pageIndex]];
UIBarButtonItem *item = [UIBarButtonItem.alloc initWithCustomView:itemView];
item.style = UIBarButtonItemStylePlain;
[items add:item];
[items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
}
[_toolbar setItems:items];
}
- (UIButton *)createButtonForItemView:(uint)pageIndex {
UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeSystem];
itemButton.frame = CGRectMake(0, 0, 100, 44);
itemButton.titleLabel.font = [UIFont systemFontOfSize:11];
itemButton.contentEdgeInsets = UIEdgeInsetsMake(30, 0, 0, 0);
itemButton.text = [_controllers[pageIndex] tabTitle];
itemButton.touchUp = ^(UIButton *sender) {
for (UIButton *button in _buttons) button.superview.tintColor = UI.toolBarInactiveButtonTextColor;
sender.superview.tintColor = UI.toolBarActiveButtonTextColor;
[self showPage:pageIndex];
};
[_buttons add:itemButton];
return itemButton;
}
- (UIToolbar *)createToolbarForItemView:(uint)pageIndex {
UIToolbar *itemToolbar = [UIToolbar.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
itemToolbar.tintColor = nil;
itemToolbar.barStyle = _toolbar.barStyle;
itemToolbar.translucent = _toolbar.translucent;
UIBarButtonItem *imageItem = [_controllers[pageIndex] tabImageItem];
imageItem.style = UIBarButtonItemStylePlain;
imageItem.tintColor = nil;
imageItem.imageInsets = UIEdgeInsetsMake(-10, 0, 0, 0);
itemToolbar.items = #[
[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil],
imageItem,
[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]
];
return itemToolbar;
}
I solved this problem as follows:
[Button **setTitleColor**:[UIColor colorWithRed:129/255.0f green:124/255.0f blue:110/255.0f alpha:1.0f] forState:**UIControlStateHighlighted**];
Im trying to add UIsearchBar to my navigation controller. Also i wish to use cancel button of UISearchBar.
UISearchBar* searchBar = [[UISearchBar alloc] init];
searchBar.frame = CGRectMake(0, 0, 300, searchBar.frame.size.height);
searchBar.translucent = NO;
searchBar.barStyle = UIBarStyleBlack;
searchBar.delegate = self;
UIView* myView = [[UIView alloc] initWithFrame:searchBar.frame];
[myView addSubview:searchBar];
UIBarButtonItem* sbItem = [[UIBarButtonItem alloc] initWithCustomView:myView];
[self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:chart,sbItem,nil]];
trouble that searchBar is inactive. it appears in navigation controller. But when i tap on it it does not response at any way. If i show cancel button it appears but also not clickable.
If i doesnt wrap UIsearchBar at UIView it work fine except it doesnt want to show me a cancel button.
UPD
IF i call
[searchBar becomeFirstResponder]
it goes to edit mode and shows me a cancel button and keyboard, but looks like view in which searchBar wrapped changes it frame params and goes on 10px down from its original appearence. And change its background from trnsparent to blackopaque
Looks like a some kind of Voodoo... So simple action takes so much time...
i think you have mistaken at search bar frame,you took search bar height as searchBar.frame.size.height,but there was no height at that time,just change it like:
UISearchBar* searchBar = [[UISearchBar alloc] init];
searchBar.frame = CGRectMake(0, 0, 300, 40);
searchBar.translucent = NO;
searchBar.barStyle = UIBarStyleBlack;
searchBar.delegate = self;
UIView* myView = [[UIView alloc] initWithFrame:searchBar.frame];
[myView addSubview:searchBar];
UIBarButtonItem* sbItem = [[UIBarButtonItem alloc] initWithCustomView:myView];
[self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:chart,sbItem,nil]];
i am sorry,i don't know what the chart is here,hope it is what you are looking for.
I'm trying to get a UISlider into my UIToolbar and to take the value from it and process it. I also want to be able to change the slider.value via other methods.
So, I set it up for the UISlider by it's self (not on a UIToolBar) and everything worked fine. Then, when I put it into the UIToolBar, the value stopped getting sent to and from it (I am NSLogging it whenever it changes and I keep getting 0 returned to me).
Here's the relevant section of my code - does anybody have any ideas?
- (void)setupToolBarAndSlider {
CGRect frame = CGRectMake(0.0, 0.0, 200.0, 30.0);
UISlider *slider = [[UISlider alloc] initWithFrame:frame];
[slider addTarget:self action:#selector(sliderValueChanged) forControlEvents:UIControlEventValueChanged];
[slider setBackgroundColor:[UIColor clearColor]];
slider.minimumValue = 0;
slider.maximumValue = 8;
slider.continuous = YES;
slider.value = questionNumberForArray;
//Change slider for UIToolbar
UIBarButtonItem *skipQuestionSlider = [[UIBarButtonItem alloc] initWithCustomView:slider];
// Set the width of aSlider
[skipQuestionSlider setWidth:400.0];
//Set up UIToolBar with Slider in it.
UIToolbar *toolBar;
CGRect rect2 = CGRectMake(0, toolBar.frame.origin.y , self.view.frame.size.width , 44);
toolBar = [[UIToolbar alloc]initWithFrame:rect2];
toolBar.barStyle = UIBarStyleBlackTranslucent;
[toolBar setItems:[NSArray arrayWithObjects:skipQuestionSlider, nil]];
[self.view addSubview:toolBar];
}
- (void)sliderValueChanged {
NSInteger roundedSliderNumber = round(skipQuestionSlider.value);
NSLog(#"Slider Value = %d", roundedSliderNumber);
}
Sam
A UIBarButtonItem (in your case, skipQuestionSlider) does not have a value property, it just houses the item. You need to reference the item you put in the UIBarButtonItem.
NSInteger roundedSliderNumber = round(slider.value);
I have customized the UINavigationBar's height to 100px and I'd like to add buttons onto this customized bar.
All is good except the button seems to want to sit on the bottom of the nav bar no matter what. I can't get it to align to the center or the top of the nav bar.
Here is the code; first I create a navigation controller in the app delegate and add one button on the right.
// set main navigation controller
temp *tempc = [[temp alloc] initWithNibName:#"temp" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:tempc];
UIBarButtonItem *navItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];
[tempc.navigationItem setRightBarButtonItem:navItem];
[self.window addSubview:self.navigationController.view];
[self.window makeKeyAndVisible];
then I resize the navigation bar in the "temp" view controller like so:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
CGRect frame = CGRectMake(0.0f, 0.0f, 320.0f, 100.0f);
[self.navigationController.navigationBar setFrame:frame];
[self.navigationController.navigationBar setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin];
}
I've also tried to add a custom view to the rightBarButtonItem but I can't get the added custom view to touch the top completely.
And the code for this unfortunate attempt:
// set main navigation controller
temp *tempc = [[temp alloc] initWithNibName:#"temp" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:tempc];
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 36.0f, 80.0f)];
[customView setBackgroundColor:[UIColor blueColor]];
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[customButton setFrame:CGRectMake(0, 22.0f, 36.0f, 36.0f)];
[customButton setTitle:#"+" forState:UIControlStateNormal];
[customView addSubview:customButton];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
Does anyone know how to vertically align UIBarButtonItems on a UINavigationBar?
This will move page title and all buttons up 20 px:
[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:-20.0 forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setBackgroundVerticalPositionAdjustment:-20.0 forBarMetrics:UIBarMetricsDefault];
The current accepted answer from alhcr (Option 1) does not work if you only have a rightBarButtonItem and no left. It is also making an assumption about the subview ordering of the UINavigationBar which is not guaranteed and could very well change in a future version of iOS. Here is a better way of customizing navigation button frames:
// UINavigationBar subclass
- (void)layoutSubviews {
[super layoutSubviews];
UINavigationItem *navigationItem = [self topItem];
for (UIView *subview in [self subviews]) {
if (subview == [[navigationItem rightBarButtonItem] customView]) {
CGRect newRightButtonRect = CGRectMake(...new rect...);
[subview setFrame:newRightButtonRect];
}
else if (subview == [[navigationItem backBarButtonItem] customView]) {
CGRect newBackButtonRect = CGRectMake(...new rect...);
[subview setFrame:newBackButtonRect];
}
}
}
Option 1:
create UINavigationBar subclass
inside this class override - (void)layoutSubviews where you will reposition UIBarButtonItems
in Interface Builder set UINavigationBar class to UINavigationBar subclass
Example:
inside subclass of UINavigationBar:
- (void)layoutSubviews {
int index = 0;
for ( UIButton *button in [self subviews] ) {
if(index == 1) {
[button setFrame:CGRectMake(5,40,60,40)]; //leftBarButtonItem
} else if(index == 2) {
[button setFrame:CGRectMake(275,40,40,40)]; //rightBarButtonItem
}
++index;
}
}
view controller:
- (void)viewDidLoad {
...
UIBarButtonItem *navItem1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];
UIBarButtonItem *navItem2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:nil action:nil];
[self.navigationItem setRightBarButtonItem:navItem1];
[self.navigationItem setLeftBarButtonItem:navItem2];
CGRect frame = CGRectMake(0.0f, 0.0f, 320.0f, 100.0f);
[self.navigationController.navigationBar setFrame:frame];
...
}
Option 2 (inserting UIBarButtonItem doesn't work):
UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0,0,320,100)];
[self.view addSubview:navigationBar];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(0,25,50,50)];
[navigationBar addSubview:button];
I found the solution of this problem by making adjustment in the Image Edge Insets of the custom button. I had the requirement in the app to increase the height of the navigation bar and after increasing the height makes the rightBarButtonItem and leftBarButtonItem images unpositioned problem.
Find the code below:-
UIImage *image = [[UIImage imageNamed:#"searchbar.png"];
UIButton* searchbutton = [UIButton buttonWithType:UIButtonTypeCustom];
[searchbutton addTarget:self action:#selector(searchBar:) forControlEvents:UIControlEventTouchUpInside];
searchbutton.frame = CGRectMake(0,0,22, 22);
[searchbutton setImage:image forState:UIControlStateNormal];
[searchbutton setImageEdgeInsets:UIEdgeInsetsMake(-50, 0,50, 0)];
// Make BarButton Item
UIBarButtonItem *navItem = [[UIBarButtonItem alloc] initWithCustomView:searchbutton];
self.navigationItem.rightBarButtonItem = navItem;