Setting a title to a UIToolBar in IOS 7 - ios

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()

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)
}

remove space below the UITabBarItem?

how do I reduce the distance between the two items?
my code:
-(void)setupRightMenuButton{
filtro = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"icon-filtro-bar"] style:UIBarButtonItemStylePlain target:self action:#selector(buttonFilter)];
busca = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"icon-busca"] style:UIBarButtonItemStylePlain target:self action:#selector(moveToSearchView)];
filtro.tintColor = [UIColor whiteColor];
busca.tintColor = [UIColor whiteColor];
filtro.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
busca.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
[self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:busca, filtro, nil] animated:YES];
}
My viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
[self setupLeftMenuButton];
[self.navigationController.navigationBar setBarTintColor: [UIColor colorWithRed:0.49 green:0.075 blue:0.082 alpha:1]]; /*#7d1315*/
[self.navigationController.navigationBar setTitleTextAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault];
[self setupRightMenuButton];
self.title = #"Músicas";
}
I tried using the filtro.imageInsets = UIEdgeInsetsMake (6, 0, -6, 0); but it did not work
Try to add buttons this way:
UIButton *but1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, width, height)];
UIView *but1View = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
[but1View addSubview:but1];
UIBarButtonItem *rightButton1 = [[UIBarButtonItem alloc] initWithCustomView:but1View];
UIButton *but2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, width, height)];
UIView *but2View = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
[but2View addSubview:but2];
UIBarButtonItem *rightButton2 = [[UIBarButtonItem alloc] initWithCustomView:but2View];
self.navigationItem.rightBarButtonItems=#[ rightButton,rightButton2];
you need to mention the postions of x and y for the both UIViews as where ou want your buttons on the nav bar.
This code works for me. Try to create a button, then set the image to it and set the buttons frame.
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
let image = UIImage(named: "your_image")!
button.setImage(image , forState: UIControlState.Normal)
// optional -------------
button.addTarget(self, action: "your_function", forControlEvents: UIControlEvents.TouchUpInside)
// ------------
button.frame = CGRectMake(0, 0, image.width, image.height)
let barButton = UIBarButtonItem(customView: button)
Create as many barButtons as you want and then add them to navigationItem:
self.navigationItem.setRightBarButtonItems([barBtn1, barBtn2], animated: false)

How to avoid UIToolbar's tintColor to change UIButtonItem button color?

In iOS7,I Created a UIBarButtonItem and init with a image which color is green.But the final appearance of that UIBarButtonItem's image is a image with the same shape but different color.The color was changed to blue.
The code is below:
_recordVoiceItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"voiceIcon"] style:UIBarButtonItemStylePlain target:self action:nil];
_textView = [[UITextView alloc] initWithFrame:CGRectMake(40, 4, 220, BOTTOM_BAR_HEIGHT - 2*4)];
_textView.layer.borderWidth = 1.f;
_rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"modeIcon"] style:UIBarButtonItemStylePlain target:self action:nil];
_bottomBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.origin.y + self.view.frame.size.height - BOTTOM_BAR_HEIGHT, self.view.frame.size.width, BOTTOM_BAR_HEIGHT)];
_bottomBar.items = #[_recordVoiceItem,[[UIBarButtonItem alloc] initWithCustomView:_textView],_rightItem];
[self.view addSubview:_bottomBar];
And I have tried to create a UIToolBar and add some items to it through Interface Builder.The appearance is fine. The color of the UIBarButtonItem's image was the origin image's color.
I doubt that I need to add some code to set some properties of the UIToolBar or UIBarButtonItem if I want to it through writing code. Could you tell me how to do?
Although it should not be required, my colored UIBarButtonItem since iOS7 are done with:
For Objective C:
UIImage* itemImage= [UIImage imageNamed:#"menu.png"]; // Colored Image
itemImage = [itemImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
_itemButton = [[UIBarButtonItem alloc] initWithImage:itemImage style:UIBarButtonItemStyleBordered target:self action:#selector(itemSelected:event:)];
UIImageRenderingModeAlwaysOriginal is the key here.
For Swift 3:
// Use the colored image menu.png as a UIBarButtonItem
if var itemImage = UIImage(named: "menu") {
itemImage = itemImage.withRenderingMode(.alwaysOriginal)
let itemButton = UIBarButtonItem(image: itemImage, style: .plain, target: self, action: #selector(self.itemSelected(_:)))
self.navigationItem.rightBarButtonItem = itemButton
}
Again, .withRenderingMode(.alwaysOriginal) is the key here.
You have to use the following code:
_bottomBar.transculantColor = No;
[_bottomBar setBackgroundColor:[UIColor clearColor]];

UIBarButtonSystemItemFlexibleSpace

Apple docs have this to say:
UIBarButtonSystemItemFlexibleSpace
Blank space to add between other items. The space is distributed equally between the other items. Other item properties are ignored when this value is set.
That's a little vague (exactly what space is distributed equally?) So I wrote a test method:
-(void) createToolbar {
BOOL stuffInTopLeftCorner = NO;
UIToolbar* bar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 1024, 44)];
self.bar = bar;
[self addSubview:bar];
UILabel* titleLabel = [[UILabel alloc]initWithFrame:CGRectZero];
titleLabel.text = #"Centered title";
titleLabel.font = [UIFont systemFontOfSize:30];
[titleLabel sizeToFit];
CGSize titleSize = [titleLabel bounds].size;
NSLog(#"titleSize is %g %g", titleSize.width, titleSize.height);
UIBarButtonItem* titleItem = [[UIBarButtonItem alloc]initWithCustomView:titleLabel];
UIBarButtonItem* flexibleSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UILabel* leftLabel = [[UILabel alloc]initWithFrame:CGRectZero];
leftLabel.text = #"Stuff in top left corner";
leftLabel.font = [UIFont systemFontOfSize:30];
[leftLabel sizeToFit];
UIBarButtonItem* topLeftCornerItem = [[UIBarButtonItem alloc]initWithCustomView:leftLabel];
NSMutableArray* items = [NSMutableArray arrayWithObjects: flexibleSpace, titleItem, flexibleSpace, nil];
if (stuffInTopLeftCorner) {
[items insertObject:topLeftCornerItem atIndex:0];
}
bar.items = items;
}
Here is what it looks like with the code as above:
And here is what it looks like if I change stuffInTopLeftCorner to YES:
It appears that adding something to the left of the title did not cause said title to move at all.
My question is -- does that mean it will always center the title, regardless of what goes on either side of it?
As best I can tell, yes, it always centers the title, assuming that is possible.

Adding a UILabel to a UIToolbar

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.

Resources