How to add a UIToolbar programmatically to an iOS app?
UIToolbar
is a subclass of UIView
, so the short answer to your question is: just like any other view.
Specifically, this is an example of how to programmatically create a toolbar. The context in this snippet is viewDidLoad
of a view controller.
UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];
[items addObject:[[[UIBarButtonItem alloc] initWith....] autorelease]];
[toolbar setItems:items animated:NO];
[items release];
[self.view addSubview:toolbar];
[toolbar release];
See UIToolbar and UIBarButtonItem documentation for details.
Add UILabel to UIToolbar Programmatically
EDITED ANSWER
The problem is with the label.
After instanciation, you must draw it with CGRect. so,
add for exemple : label.frame = CGRect(x: 20, y:20, width: 100, height: 50)
Result:
let label = UILabel()
label.text = "Example"
label.frame = CGRect(x: 20, y:20, width: 100, height: 50)
Build Toolbar programmatically
Try this if it helps:
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
let homeButton = UIBarButtonItem(title: "H", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let flexibleSpace1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
let addButton = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let flexibleSpace2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
let loveButton = UIBarButtonItem(title: "Love", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let arr: [Any] = [flexibleSpace, homeButton, flexibleSpace1, addButton, flexibleSpace2, loveButton]
setToolbarItems(arr as? [UIBarButtonItem] ?? [UIBarButtonItem](), animated: true)
super.viewDidAppear(animated)
You can add flexible space on left side of 'H' too to get left space.
Adding UIToolbar programmatically
You need to set the toolbar's autosizingMask
to the "flexible top margin" value.
Also, your code deals with the toolBar
variable, the bottomToolbar
property, and the _bottomToolbar
ivar. Either use the property or the ivar. It's confusing to use both like you are.
How can I add a toolbar above the keyboard?
UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 50)];
numberToolbar.barStyle = UIBarStyleBlackTranslucent;
numberToolbar.items = [NSArray arrayWithObjects:
[[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)],
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],
nil];
[numberToolbar sizeToFit];
phonenumberTextField.inputAccessoryView = numberToolbar;
To Dismiss Keyboard:
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
Swift 3:
let numberToolbar = UIToolbar(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 50))
numberToolbar.barStyle = UIBarStyle.Default
numberToolbar.items = [
UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelNumberPad"),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneWithNumberPad")]
numberToolbar.sizeToFit()
phonenumberTextField.inputAccessoryView = numberToolbar
Swift 4.2:
let numberToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
numberToolbar.barStyle = .default
numberToolbar.items = [
UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelNumberPad)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneWithNumberPad))]
numberToolbar.sizeToFit()
phonenumberTextField.inputAccessoryView = numberToolbar
...
@objc func cancelNumberPad() {
//Cancel with number pad
}
@objc func doneWithNumberPad() {
//Done with number pad
}
How to add a UIToolbar to a UITableViewController programmatically?
The simpler thing to do is to build your project on top of a UINavigationController
. It already has a toolbar, it's just hidden by default. You can reveal it by toggling the toolbarHidden
property, and your table view controller will be able to use it as long as it's in the navigation controller hierarchy.
In your app delegate, or in the object your app delegate passes control to, create the navigation controller with your UITableViewController
as the root view controller:
- ( void )application: (UIApplication *)application
didFinishLaunchingWithOptions: (NSDictionary *)options
{
MyTableViewController *tableViewController;
UINavigationController *navController;
tableViewController = [[ MyTableViewController alloc ]
initWithStyle: UITableViewStylePlain ];
navController = [[ UINavigationController alloc ]
initWithRootViewController: tableViewController ];
[ tableViewController release ];
/* ensure that the toolbar is visible */
navController.toolbarHidden = NO;
self.navigationController = navController;
[ navController release ];
[ self.window addSubview: self.navigationController.view ];
[ self.window makeKeyAndVisible ];
}
Then set the toolbar items in your MyTableViewController
object:
- ( void )viewDidLoad
{
UIBarButtonItem *buttonItem;
buttonItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Back"
style: UIBarButtonItemStyleBordered
target: self
action: @selector( goBack: ) ];
self.toolbarItems = [ NSArray arrayWithObject: buttonItem ];
[ buttonItem release ];
/* ... additional setup ... */
}
add UIToolBar in swift
So I had a similar problem, but it wasn't due to my code. Your code works as well. The issue most likely lies with where you are running that code. Make sure it is in viewDidLoad() or a similar view lifecycle function. Put a breakpoint in the function, and when you run your app, see if it hits it. If it doesn't hit it, you may have a problem similar to the one described in this post (When using a UINavigationController the viewWillAppear or viewDidAppear methods of my controller are not called)
Adding buttons to toolbar programmatically in swift
The usual way to do that is to create the array of toolbar items and then assign the array to the items
property of the toolbar.
self.navigationController?.isToolbarHidden = false
var items = [UIBarButtonItem]()
items.append(
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
)
items.append(
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(onClickedToolbeltButton(_:)))
)
toolbarItems = items
Add UIBarButtonItem to UIToolbar programmatically?
UIToolbar* toolbar = [[UIToolbar alloc]
initWithFrame:CGRectMake(0, 0, 320, 45)];
[toolbar setBarStyle: UIBarStyleBlackOpaque];
// create an array for the buttons
NSMutableArray* BarbuttonsArray = [[NSMutableArray alloc] initWithCapacity:5];
// create a clearAll button
UIBarButtonItem * clearAllButton = [[UIBarButtonItem alloc] initWithTitle:@"Clear All"
style:UIBarButtonItemStylePlain
target:self
action:@selector(clearAllAction:)];
clearAllButton.style = UIBarButtonItemStyleBordered;
[BarbuttonsArray addObject:clearAllButton];
[clearAllButton release];
// create a calculate button
UIBarButtonItem *calculateButton = [[UIBarButtonItem alloc]initWithTitle:@"Calculate"
style:UIBarButtonItemStylePlain
target:self
action:@selector(calculateButton:)];
calculateButton.style = UIBarButtonItemStyleBordered;
[BarbuttonsArray addObject:calculateButton];
[calculateButton release];
// create a settingButton
UIBarButtonItem *settingButton = [[UIBarButtonItem alloc]initWithTitle:@"Setting"
style:UIBarButtonItemStylePlain
target:self
action:@selector(settingButton:)];
settingButton.style = UIBarButtonItemStyleBordered;
[BarbuttonsArray addObject:settingButton];
[settingButton release];
// create a buyNowButton
UIBarButtonItem *buyNowButton = [[UIBarButtonItem alloc]initWithTitle:@"Buy Now"
style:UIBarButtonItemStylePlain
target:self
action:@selector(buyNowButton:)];
buyNowButton.style = UIBarButtonItemStyleBordered;
[BarbuttonsArray addObject:buyNowButton];
[buyNowButton release];
// put the BarbuttonsArray in the toolbar and release them
[toolbar setItems:BarbuttonsArray animated:NO];
[BarbuttonsArray release];
// place the toolbar into the navigation bar
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolbar];
[toolbar release];
//before using these lines of code you have to alloc and make the property of UINavigationController in your appDelegate
Try to use this may help you
Related Topics
How to Make Both Header and Footer in Collection View with Swift
Ios: Place Uiview on Top of Uitableview in Fixed Position
How to Implement "Share Button" in Swift
How to Push Two View Controllers But Animate Transition Only for the Second One
Run Repeating Nstimer with Gcd
Error While Build Project Xcode Says:"You Don't Have Permission"
How to Stop Uitableview from Clipping Uitableviewcell Contents in iOS 7
Check If App Is Ad-Hoc|Dev|App-Store Build at Run Time
iOS 5 Sdk Is Gone After Upgrade to Xcode 4.5
Xcode 9 - Localization Issue Warning Storyboard
Xcode 4.2 Jumps to Main.M Every Time After Stopping Simulator
Getting Video Snapshot for Thumbnail
How to Define the Size of a Collectionview on Rotate
Firebase Dynamic Link Not Opening the App iOS
Drop Cap with Nsattributedstring
Swift - Uiimagepickercontroller - How to Use It