Adding a UILabel to a UIToolbar - ios

I'm trying to add a label to my toolbar. Button works great, however when I add the label object, it crashes. Any ideas?
UIBarButtonItem *setDateRangeButton = [[UIBarButtonItem alloc] initWithTitle:#"Set date range"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(setDateRangeClicked:)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
label.text = #"test";
[toolbar setItems:[NSArray arrayWithObjects:setDateRangeButton,label, nil]];
// Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];
// Reload the table view
[self.tableView reloadData];

Have a look into this
[[UIBarButtonItem alloc] initWithCustomView:yourCustomView];
Essentially every item must be a "button" but they can be instantiated with any view you require. Here is some example code. Note, since other buttons are typically on the toolbar, spacers are placed on each side of the title button so it stays centered.
NSMutableArray *items = [[self.toolbar items] mutableCopy];
UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:spacer];
[spacer release];
self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 11.0f, self.view.frame.size.width, 21.0f)];
[self.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:18]];
[self.titleLabel setBackgroundColor:[UIColor clearColor]];
[self.titleLabel setTextColor:[UIColor colorWithRed:157.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0]];
[self.titleLabel setText:#"Title"];
[self.titleLabel setTextAlignment:NSTextAlignmentCenter];
UIBarButtonItem *spacer2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:spacer2];
[spacer2 release];
UIBarButtonItem *title = [[UIBarButtonItem alloc] initWithCustomView:self.titleLabel];
[items addObject:title];
[title release];
[self.toolbar setItems:items animated:YES];
[items release];

For those using Interface Builder to layout your UIToolBar, it is also possible to do this using Interface Builder alone.
To add a UILabel to a UIToolBar you need to add a generic UIView object to your UIToolBar in IB by dragging a new UIView object over your UIToolBar. IB will automatically create a UIBarButtonItem that will be initialized with your custom UIView. Next add a UILabel to the UIView and edit the UILabel graphically to match your preferred style. You can then visually set up your fixed and/or variable spacers as desired to position your UILabel appropriately.
You must also set the background of both the UILabel and the UIView to clearColor to get the UIToolBar to show through correctly under the UILabel.

I found answerBot's answer very useful, but I think I found an even easier way, in Interface Builder:
create a UIBarButtonItem and add it to your Toolbar in Interface
Builder
Uncheck "enabled" for this BarButtonItem
plug this BarButtonItem to a property in your class (this is in
Swift, but would be very similar in Obj-C):
#IBOutlet private weak var lastUpdateButton: UIBarButtonItem! // Dummy barButtonItem whose customView is lastUpdateLabel
add another property for the Label itself:
private var lastUpdateLabel = UILabel(frame: CGRectZero)
in viewDidLoad, add the following code to set the properties of your
label, and add it as the customView of your BarButtonItem
// Dummy button containing the date of last update
lastUpdateLabel.sizeToFit()
lastUpdateLabel.backgroundColor = UIColor.clearColor()
lastUpdateLabel.textAlignment = .Center
lastUpdateButton.customView = lastUpdateLabel
To update the UILabel text:
lastUpdateLabel.text = "Updated: 9/12/14, 2:53"
lastUpdateLabel.sizeToFit()
Result :
You have to call lastUpdateLabel.sizetoFit() each time you update the label text

One of the things I'm using this trick for is to instantiate a UIActivityIndicatorView on top of the UIToolBar, something that otherwise wouldn't be possible. For instance here I have a UIToolBar with 2 UIBarButtonItem, a FlexibleSpaceBarButtonItem, and then another UIBarButtonItem. I want to insert a UIActivityIndicatorView into the UIToolBar between the flexible space and the final (right-hand) button. So in my RootViewController I do the following,
- (void)viewDidLoad {
[super viewDidLoad];// Add an invisible UIActivityViewIndicator to the toolbar
UIToolbar *toolbar = (UIToolbar *)[self.view viewWithTag:767];
NSArray *items = [toolbar items];
activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
NSArray *newItems = [NSArray arrayWithObjects:[items objectAtIndex:0],[items objectAtIndex:1],[items objectAtIndex:2],
[[UIBarButtonItem alloc] initWithCustomView:activityIndicator], [items objectAtIndex:3],nil];
[toolbar setItems:newItems];}

Details
Xcode 10.2.1 (10E1001), Swift 5
Full sample
import UIKit
class ViewController: UIViewController {
private weak var toolBar: UIToolbar?
override func viewDidLoad() {
super.viewDidLoad()
var bounds = UIScreen.main.bounds
let bottomBarWithHeight = CGFloat(44)
bounds.origin.y = bounds.height - bottomBarWithHeight
bounds.size.height = bottomBarWithHeight
let toolBar = UIToolbar(frame: bounds)
view.addSubview(toolBar)
var buttons = [UIBarButtonItem]()
buttons.append(UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.action)))
buttons.append(UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(ViewController.action)))
buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
buttons.append(ToolBarTitleItem(text: "\(NSDate())", font: .systemFont(ofSize: 12), color: .lightGray))
buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
buttons.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(ViewController.action)))
toolBar.items = buttons
self.toolBar = toolBar
}
#objc func action() { print("action") }
}
class ToolBarTitleItem: UIBarButtonItem {
init(text: String, font: UIFont, color: UIColor) {
let label = UILabel(frame: UIScreen.main.bounds)
label.text = text
label.sizeToFit()
label.font = font
label.textColor = color
label.textAlignment = .center
super.init()
customView = label
}
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
}
Result

Similar to Matt R I used interface builder. But I wanted to have 1 UIWebView inside instead so that i can have some text bolded and other text not (like the mail app). So
Add the webview instead.
Uncheck opaque
Make sure background is clear color
Hook everything up with IBOutlet
Use the below html to have a transparent background so the toolbar shines through
Code:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *html = [NSString stringWithFormat:#"<html><head><style>body{font-size:11px;text-align:center;background-color:transparent;color:#fff;font-family:helvetica;vertical-align:middle;</style> </head><body><b>Updated</b> 10/11/12 <b>11:09</b> AM</body></html>"];
[myWebView loadHTMLString:html baseURL:baseURL];

If you want to adding a view up the toolbar view you can try this:
[self.navigationController.tabBarController.view addSubview:yourView];

Try this:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(140 , 0, 50, 250)];
[label setBackgroundColor:[UIColor clearColor]];
label.text = #"TEXT";
UIView *view = (UIView *) label;
[self.barItem setCustomView:view];
Note: self.barItem is a UIBarButtonItem added from the object library and placed between two flexible spaces.
another way is to remove the [self.barItem setCustom:view] line and change the parameters of the label (width) so that it fills the entire toolbar and set the alignment to middle and the font by yourself in code,

could use a disabled BarButtonItem
let resultsLabel = UIBarButtonItem(title: "number of results", style: .plain, target: self, action: nil)
resultsLabel.isEnabled = false

A solution to this in Swift
One way you could do this is by creating a UILabel and then adding it as custom view to a UIBarButtonItem which you then add to the toolbar.
For example:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setToolbarHidden(false, animated: false)
let textLabel = UILabel()
textLabel.font = UIFont.systemFont(ofSize: 17)
textLabel.text = "Text Label" // Change this to be any string you want
let textButton = UIBarButtonItem(customView: textLabel)
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
setToolbarItems([spacer, textButton, spacer], animated: false)
}
}
NOTE: The flexibleSpace's position the label in the centre of the tool bar
Here's a screenshot of what this would look like:
NOTE: Without a tab bar the toolbar would take up the bottom of the screen.

Related

Custom Keyboard InputAccessoryView not visible in iOS 11

I have implemented Custom input accessory view it was working fine till iOS 10.3.1. But it's not visible in iOS 11 beta.
Have anyone experience this issue?
The question you ask does not have much detail. But I had the same problem when using an inputAccessoryView and a custom inputView for the textfield.
And resolved this on iOS11 by setting the custom inputView's autoresizingMask to .flexibleHeight.
yourCustomInputView.autoresizingMask = .flexibleHeight
Hope this resolves the issue. If not maybe provide some more information?
Here is how I add the input accessory, incase this is of more help (as extension of textfield):
public extension UITextField {
public func addToolbarInputAccessoryView(barButtonItems: [UIBarButtonItem],
textColour: UIColor,
toolbarHeight: CGFloat = 44,
backgroundColour: UIColor = .white) {
let toolbar = UIToolbar()
toolbar.frame = CGRect(x: 0, y: 0, width: bounds.width, height: toolbarHeight)
toolbar.items = barButtonItems
toolbar.isTranslucent = false
toolbar.barTintColor = backgroundColour
toolbar.tintColor = textColour
inputAccessoryView = toolbar
}
}
And then on the inputView (not the inputAccessoryView), I was using a date picker for example - just make sure that the date picker's autoresizing mask is set to flexible height.
PSA: If you use a UIToolbar as your custom view, it's currently broken in iOS 11 GM.
Instead of loosing your hair on how to fix it, just change it to UIView.
You'll loose the blur effect but it will work.
Beta 3 has just come out and some people said it solved the problem, but for me it didn't.
However I tried setting the accessory view to something stupid (100pxls high) and spotted that the Undo/Redo/Paste bar on the iPads was incorrectly sitting over the top of my accessory bar.
So I added the following code to get rid of Apples bar (it was pointless for my custom picker anyway) and the problem went away
Hope this helps somebody
- (void)textFieldDidBeginEditing:(UITextField*)textField
{
UITextInputAssistantItem* item = [textField inputAssistantItem];
item.leadingBarButtonGroups = #[];
item.trailingBarButtonGroups = #[];
}
To avoid the inputAccessoryView issue in iOS 11 for UITextField and UITextView, just use the following code:
UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
self.monthPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
self.monthPickerView.backgroundColor = [UIColor whiteColor];
self.monthPickerView.delegate = self;
self.monthPickerView.dataSource = self;
[inputView addSubview:self.monthPickerView];
cell.monthTextField.inputView = inputView ;
self.monthTextField.inputAccessoryView = [self doneButtonAccessoryView];
// doneButtonAccessoryView Method
-(UIToolbar*)doneButtonAccessoryView
{
UIToolbar *kbToolbar = [[UIToolbar alloc] init];
[kbToolbar sizeToFit];
[kbToolbar setBarTintColor:[UIColor whiteColor]];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:#"Done"
style:UIBarButtonItemStyleDone target:self
action:#selector(doneClicked)];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel"
style:UIBarButtonItemStyleDone target:self
action:#selector(cancelClicked)];
NSDictionary *attrDict;
attrDict = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"Helvetica-Bold" size:16.0], NSFontAttributeName, nil];
[doneButton setTitleTextAttributes:attrDict forState:UIControlStateNormal];
UIBarButtonItem *flexWidth = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:self action:nil];
[kbToolbar setItems:[NSArray arrayWithObjects:cancelButton,flexWidth, doneButton, nil]];
return kbToolbar;
}
UIToolBar is broken in iOS 11. But you can get the same thing done using UIView as inputAccessoryView. Sample code snippet here:
CGFloat width = [[UIScreen mainScreen] bounds].size.width;
UIView* toolBar = [[UIView alloc] initWithFrame:CGRectMake(0.0f,0.0f, width, 44.0f)];
toolBar.backgroundColor = [UIColor colorWithRed:0.97f green:0.97f blue:0.97f alpha:1.0f];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20.0 , 0.0f, width, 44.0f)];
[titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:13]];
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setTextColor:[UIColor redColor]];
[titleLabel setText:#"Title"];
[titleLabel setTextAlignment:NSTextAlignmentLeft];
[toolBar addSubview:titleLabel];
UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[doneBtn setTitle:#"Done" forState:UIControlStateNormal];
doneBtn.tintColor = [UIColor colorWithRed:(float)179/255 green:(float)27/255 blue:(float)163/255 alpha:1];
[doneBtn.titleLabel setFont:[UIFont fontWithName:#"Helvetica" size:16]];
[doneBtn addTarget:self action:#selector(btnTxtDoneAction) forControlEvents:UIControlEventTouchUpInside];
[doneBtn setFrame:CGRectMake(width-70, 6, 50, 32)];
[toolBar addSubview:doneBtn];
[toolBar sizeToFit];
txtMessageView.inputAccessoryView = toolBar;
Hope this help..:)
I've had the same issue and I've found out that removing all of the bottom, top, leading, training, left, right constraints for the
view that is assigned accessoryView solved it.
Swift 4 solution
let toolBarRect = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44)
let toolBar = UIView(frame: toolBarRect)
toolBar.backgroundColor = .lightGray
let nextButton = UIButton()
nextButton.setTitleColor(.black, for: .normal)
nextButton.setTitle("Next", for: .normal)
nextButton.addTarget(self, action: #selector(self.onNextButtonTouch), for: .touchUpInside)
nextButton.translatesAutoresizingMaskIntoConstraints = false
toolBar.addSubview(nextButton)
NSLayoutConstraint.activate(
[
nextButton.heightAnchor.constraint(equalToConstant: Constants.keyboardToolBarHeight),
nextButton.trailingAnchor.constraint(equalTo: toolBar.trailingAnchor, constant: -16),
nextButton.centerYAnchor.constraint(equalTo: toolBar.centerYAnchor, constant: 0)
]
)
self.yourTextField.inputAccessoryView = toolBar
Just in case someone might still need the solution, here's what I did (IOS 12.1);
private func initSearchBox() {
// Add Done button on keyboard
txtSearch.delegate = self
let tbrDone = UIToolbar()
let btnDone = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(btnDone_tapped))
tbrDone.items = [btnDone]
tbrDone.sizeToFit()
self.txtSearch.inputAccessoryView = tbrDone
}
#objc func btnDone_tapped() {
view.endEditing(true)
}

Updating A UIView in customView field of UIBarButtonItem

I am keeping a score of a game in the navigation bar.
I am trying to update the UILabel in UIBarButtonItem's customView.
After I call setText on UILabel, it does not get updated.
I tried to change its color just to test, that also does not work.
I tried to update the UILabel by calling setNeedsDisplay
I tried to update the customView in UIBarButtonItem by calling setNeedsDisplay.
Non of that actually updates the view.
I debugged and the code executes and prints the correct value on console when it gets to the line where I NSLog.
I also tried to update the whole view of navController by calling. (Current code does that below)
What is the right way to update/refresh the customView field of UIBarButtonItem
UIBarButtonItem* backUIButton =[view.navigationItem.rightBarButtonItems objectAtIndex:1];// I have 2 items in rightBarButtonList
UIView* settingFrame =backUIButton.customView;
for (UIView *i in settingFrame.subviews){
if([i isKindOfClass:[UILabel class]]){
UILabel *newLbl = (UILabel *)i;
if(newLbl.tag == 1){
/// Write your code
NSString *inStr = [NSString stringWithFormat:#"%ld", [Utility getCoins] ];
NSLog(#"data : %#",inStr);
[newLbl setTextColor:[UIColor redColor]];
[newLbl setText:inStr];
[view.navigationController.view setNeedsDisplay];
}
}
}
Thanks
I will just keep a property of the label
For example
I keep a property
#property (weak,nonatomic)UILabel * numlabel;
Here I create the custom bar item
UIView * customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,80,40)];
UILabel * label = [[UILabel alloc] init];
label.text = #"1";
label.frame = CGRectMake(0,0,80,40);
self.numlabel = label;
[customView addSubview:label];
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:customView];
self.navigationItem.leftBarButtonItem = item;
Then When I need to change
self.numlabel.text = #"2";
I have test with my XCode,it works well
#interface HomeViewController ()
{
UILabel *label;//Globally declare the label to make changes
}
- (void)viewDidLoad
{
[super viewDidLoad];
label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
label.text = #"First";
UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:label];//set label as barButtonItem
self.navigationItem.rightBarButtonItem = barButton;
}
here, i updated the label with a buttonAction
- (IBAction)buttonAction:(id)sender
{
label.text = #"second";//successfully updated the label
}

Align UIBarButtonItem Title to prevent overlapping of other Buttons?

I want to create a header toolbar like shown in the image below. It is from the web view of the Twitter app.
I created a UIToolbar and put it at the top. Then I inserted the Buttons left and right and changed the Identifier to get the correct symbols.
My problem is the text in the middle. I create a UIBarButtonItem and placed it between the buttons. Here is my Problem.
How to I achieve that the UIBarButtonItem title does not overlap the left and the right button when the title is to long?
In my case:
How do I achieve that the title gets ... at the end if it gets to long?
How can I set the sub title?
How can I achieve that the button is not clickable, i.e., has color black?
Edit Using the answer from #Viral Savaj: Here is what it looks like:
To test if the title is too long, you should use character counting. Let myHeaderBarString represent your string for the title. You will probably have to adjust this number to find the right length before it gets truncated.
if count(myHeaderBarString) > 40 {
myHeaderBarString = myHeaderBarString.substringToIndex(40)
myHeaderBarString.append("...")
}
For a subtitle, you should insert a new view with a UILabel inside it.
You can set custom title view to the navigation bar like this way.
//To hide default back button
self.navigationItem.hidesBackButton=YES;
//Title View for Navigation
UIView *navTitle1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
[navTitle1 setBackgroundColor:[UIColor lightGrayColor]];
//Left View button and separator
UIButton *crossBarButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
[crossBarButton setTitle:#"X" forState:UIControlStateNormal];
//Center view with two buttons and seprator for them
UILabel *topTitle = [[UILabel alloc] initWithFrame: CGRectMake(50,0, self.view.bounds.size.width-100, 22)];
topTitle.text = #"text";
topTitle.font = [UIFont systemFontOfSize:25];
topTitle.lineBreakMode = NSLineBreakByCharWrapping;
UILabel *subTitle = [[UILabel alloc] initWithFrame: CGRectMake(50,20, self.view.bounds.size.width-100, 18)];
subTitle.text = #"subtext";
subTitle.font = [UIFont systemFontOfSize:18];
subTitle.lineBreakMode = NSLineBreakByCharWrapping;
//Right button with seprator before that
UIButton *uploadBarButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-50, 0, 44, 44)];
[uploadBarButton setTitle:#"U" forState:UIControlStateNormal];
[navTitle1 addSubview:crossBarButton];
[navTitle1 addSubview:topTitle];
[navTitle1 addSubview:subTitle];
[navTitle1 addSubview:uploadBarButton];
self.navigationItem.titleView = navTitle1;
You can refer THIS for more detail.
Use BarButtonItem.customView, it works.
let button = UIButton(frame: CGRectMake(0,0,200,40))
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.setTitle("gogogogogogogogoogogogogogogogogogoogo", forState: .Normal)
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
button.addTarget(self, action: "showMessage:", forControlEvents: .TouchUpInside)
let rightBarButtonItem = UIBarButtonItem()
rightBarButtonItem.customView = button
self.navigationItem.rightBarButtonItem = rightBarButtonItem

Setting a title to a UIToolBar in IOS 7

I have a UIToolBar button declared below:
UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, 64.0);
I also have a UIBarButtonItem that gets added in on the left as a back button. But how do I just add a centered label title to the UIToolbar?
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 150, 20)];
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor blackColor];
lblTitle.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:lblTitle];
UIBarButtonItem *typeField = [[UIBarButtonItem alloc] initWithCustomView:lblTitle];
toolBar.items = [NSArray arrayWithArray:[NSArray arrayWithObjects:backButton,spaceBar,lblTitle, nil]];
This will solve your problem i think.
Create a UILabel and add it as an item of the toolbar:
UIBarButtonItem *toolBarTitle = [[UIBarButtonItem alloc] initWithCustomView:myLabel];
If you want to center it, add flexible spaces on the sides:
UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]
None of the other answers were as copy and pasteable as I wanted, so...
UILabel *toolbarLabel = [[UILabel alloc] initWithFrame:CGRectZero];
toolbarLabel.text = #"Text in yo toolbar";
[toolbarLabel sizeToFit];
toolbarLabel.backgroundColor = [UIColor clearColor];
toolbarLabel.textColor = [UIColor grayColor];
toolbarLabel.textAlignment = NSTextAlignmentCenter;
UIBarButtonItem *labelItem = [[UIBarButtonItem alloc] initWithCustomView:toolbarLabel];
UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[self setToolbarItems:#[flexible, labelItem, flexible] animated:false];
This assumes you have the toolbar showing through your navigation controller (to show it from any View Controller that's shown by a navigation controller, [self.navigationController setToolbarHidden:NO animated:YES];)
It looks something like this (iOS 9):
UIToolbar doesn't have a title property. As others suggested you need to add a UILabel as a title.
Or you can use UINavigationBar instead and initialize using - (id)initWithTitle:(NSString *)title;
Here is a Swift 2.2 implementation of Aaron Ash's answer
let toolbarLabel = UILabel(frame: CGRectZero)
toolbarLabel.text = "Text in yo toolbar"
toolbarLabel.sizeToFit()
toolbarLabel.backgroundColor = UIColor.clearColor()
toolbarLabel.textColor = UIColor.grayColor()
toolbarLabel.textAlignment = .Center
let labelItem = UIBarButtonItem.init(customView: toolbarLabel)
let flexible = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target:nil, action:nil)
self.setToolbarItems([flexible, labelItem, flexible], animated: false)
Here is a Swift 3 implementation:
let topBarTitleLabel = UILabel.init(frame: (CGRect.init(origin: CGPoint.init(x: 0.0, y: 0.0), size: CGSize.init(width: 0.0, height: 0.0))))
topBarTitleLabel.text = "Text in yo toolbar"
topBarTitleLabel.sizeToFit()
topBarTitleLabel.backgroundColor = UIColor.clear
topBarTitleLabel.textColor = UIColor.black
topBarTitleLabel.textAlignment = NSTextAlignment.center
let topBarButtonItemTitleLabel = UIBarButtonItem.init(customView: topBarTitleLabel)
let flexibleBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
self.topToolBar.setItems([flexibleBarButtonItem, topBarButtonItemTitleLabel, flexibleBarButtonItem], animated: false)
self.topToolBar.setNeedsLayout()

programmatically adding button to UIToolbar

I am programmatically creating a UIToolbar with this code:
pickerTB = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:pickerTB];
How do i add one single button to it? It needs to say "Done" and the button must be able to call a method later on.
Try this, If you want to add DONE button on right side of uitoolbar then add flexible button before done button
UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneButton)];
NSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];
[toolbar setItems:itemsArray];
-(void)doneButton
{
}
// change toolbar style
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
//change bar button color
[doneButton setTintColor:[UIColor blackColor]];
pickerTB.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(done:)],nil];
This code will really helpful to add button to the UIToolbar present in keyboard or pickerview.
For example:
If you want "Done" button to be inserted in the toolbar of the pickerview. you just have to follow simple steps as follows.
Step 1:
Have to include this code inside "viewDidLoad" to create "Done" button in UIToolbar. "textBoxText" is the name of the Text field.
// create done button in toolbar.
doneToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
doneToolbar.barStyle = UIBarStyle.Default
doneToolbar.items = [UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(FirstViewController.PickerDoneButtonTapped))]
doneToolbar.sizeToFit()
textBoxText.inputAccessoryView = doneToolbar
Step 2:
Code the function of "Done" button that has included in the UIToolbar. I have given that if "Done" button is tapped the PickerView have to disable.
func PickerDoneButtonTapped()
{
textBoxText.resignFirstResponder()
}
Step 3:
Have to call the function in "viewDidload"
self.PickerDoneButtonTapped()
Output:

Resources