How to add UIBarButtonItem to right side of UIToolBar? - ios

I have to use
[addButton,addButton,addButton,addButton,addButton,addButton,addButton]
to put addButton to right side of the bar. What is the correct way?
func addBtnToKeyboardTop() {
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
keyboardToolbar.isTranslucent = false
keyboardToolbar.barTintColor = UIColor.lightGray
let addButton = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(CreateClubTVC.hideKeyboard)
)
addButton.tintColor = UIColor.black
keyboardToolbar.items = [addButton,addButton,addButton,addButton,addButton,addButton,addButton]
membershipFee.inputAccessoryView = keyboardToolbar
}

For that you have to add a flexible space before the button.
Swift 3
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
//creating flexible space
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
// creating button
let addButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(CreateClubTVC.hideKeyboard))
// adding space and button to toolbar
keyboardToolbar.setItems([flexibleSpace,addButton], animated: false)
// adding toolbar to input accessory view
membershipFee.inputAccessoryView = keyboardToolbar

Related

iOS toolbar barbuttonitem spacer

I am trying to add two bar buttons to toolbar in iOS [Cancel] & [Save] on right and left side accordingly.
I used a third bar button [Spacer] and set it to be [.flexiblewidth] Otherwise, when adding it only the left button appears [Cancel] and the [Spacer] & and [Save] which have to be next disappearing ?
the screen shot is in the link:
https://ibb.co/cZsaVV
let pickerView = UIPickerView()
override func viewDidLoad() {
pickerView.addSubview(self.setToolBar())
}
func setToolBar() -> UIToolbar {
let toolBar = UIToolbar()
toolBar.isTranslucent = true
toolBar.backgroundColor = UIColor.clear
let barButtonAttr = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15),
NSAttributedString.Key.foregroundColor : UIColor.black]
// [Save] BarButtonItem
let saveBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.save, target: self, action: nil)
saveBarButtonItem.setTitleTextAttributes(barButtonAttr, for: .normal)
// [Cancel] BarButtonItem
let cancelBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: nil)
cancelBarButtonItem.setTitleTextAttributes(barButtonAttr, for: .normal)
let spacerBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace ,
target: self, action: nil)
spacerBarButtonItem.setTitleTextAttributes(barButtonAttr, for: .normal)
// add BarButtonItems to toolBar
toolBar.items = [cancelBarButtonItem,spacerBarButtonItem,saveBarButtonItem]
toolBar.sizeToFit()
return toolBar
}
func createAccessoryViewWithTarget(_ target: AnyObject, width: CGFloat) -> UIView {
// Previous button
let previousButton = UIBarButtonItem(title: "Previous", style: .plain, target: target, action: #selector(self.moveToPreviousTextField))
previousButton.tintColor = UIColor.white
//Next button
let nextButton = UIBarButtonItem(title: "Next", style: .plain, target: target, action: #selector(self.moveToNextTextField))
nextButton.tintColor = UIColor.white
// Dismiss/close/done button
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: target, action: #selector(self.keyboardDoneButtonTapped))
doneButton.tintColor = UIColor.white
let keyboardToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: width, height: 44))
keyboardToolbar.barStyle = .black
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
var itemsArray = [UIBarButtonItem]()
itemsArray.append(previousButton)
itemsArray.append(fixedSpace)
itemsArray.append(nextButton)
itemsArray.append(flexSpace)
itemsArray.append(doneButton)
keyboardToolbar.items = itemsArray
keyboardToolbar.sizeToFit()
return keyboardToolbar
}
This one is old code may be swift3 I guess. Here Im adding 3 buttons previous next and done button. flexible space and fixed space are used for spaces between buttons. Important to note here is the order that you adding your barbutton items. In your case use flexible space to place your 2 buttons on right and left end in the order of left end button, flexible space, right end button.
I've got the solution finally.
I am adding the ToolBar to the PickerView and then calling UIToolBar.SizeToFit() which is must in all cases.
the issue was I had to change the picker view size later in this case the size of subview ToolBar is not adapting with the new size coordination of pickerView. So the solution simply to call again ToolBar.SizeToFit() after any modification of parent view. here's snap of the code:
// popupView is custom UIPickerView
popupView.frame = CGRect(x:0, y:0, width:100, height:100)
// toolBar is an object of UIToolBar of the custom UIPickerView AddCurrencyPicker
(popupView as! AddCurrencyPicker).toolBar.sizeToFit()

Done Button Issue In Toolbar

I added a toolbar with done and cancel buttons and everything was right. Suddenly, the done and cancel text is hidden. The buttons exist and are clickable but with no text. I tried everything but same problem.
This is the code regarding the toolbar:
func createDatePicker(){
//format for datepicker display
datePicker.datePickerMode = .date
datePicker.minimumDate = Date()
datePicker.backgroundColor = UIColor.white
// ToolBar
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.backgroundColor = UIColor(red: 253/255, green: 184/255, blue: 20/35, alpha: 1.0)
//datePicker.tintColor = UIColor.blue
toolBar.tintColor = UIColor.blue
toolBar.sizeToFit()
toolBar.isUserInteractionEnabled = true
//add a done button on this toolbar
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneClicked))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelClicked))
toolBar.setItems([cancelButton,spaceButton,doneButton], animated: true)
testfield.inputAccessoryView = toolBar
testfield.inputView = datePicker
self.view.addSubview(testfield)
}
And this is the result:
Here is the Code is am using based on your code and it is working perfectly fine for me
import UIKit
class ViewController: UIViewController {
var datePicker = UIDatePicker()
var testfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
createDatePicker()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func createDatePicker(){
// TextField
testfield = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
testfield.placeholder = "testfiled"
self.view.addSubview(testfield)
//format for datepicker display
datePicker.datePickerMode = .date
datePicker.minimumDate = Date()
datePicker.backgroundColor = UIColor.white
// ToolBar
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.backgroundColor = UIColor(red: 253/255, green: 184/255, blue: 20/35, alpha: 1.0)
//datePicker.tintColor = UIColor.blue
toolBar.tintColor = UIColor.blue
toolBar.sizeToFit()
toolBar.isUserInteractionEnabled = true
//add a done button on this toolbar
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneClicked))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelClicked))
toolBar.setItems([cancelButton,spaceButton,doneButton], animated: true)
testfield.inputAccessoryView = toolBar
testfield.inputView = datePicker
}
#objc func doneClicked(){
}
#objc func cancelClicked(){
}
}
Please try to test on both Device And Simulator
Or try clean(shift+cmd+k) project before build this helps in most of cases.
Result
I did a WORK AROUND by adding image to the done and cancel button
let DonebuttonIcon = UIImage(named: "done-calender.png")
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(doneClicked))
doneButton.image = DonebuttonIcon
doneButton.tintColor = UIColor.gray
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let CancelbuttonIcon = UIImage(named: "cancel-calender.png")
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.done, target: self, action: #selector(cancelClicked))
cancelButton.image = CancelbuttonIcon
cancelButton.tintColor = UIColor.gray

Centering UIBarButtonItem Plain in toolbar vertically

dI have a uitoolbar that has two buttons, First one is a System Button item Camera, second is a System item flixable space, and third is a Plain Button with text. However, when the toolbar comes up, the first button is centered but the Plain button is not.
Any idea on how to change the right button to center vertically?
This is the code on setting up the toolbar:
let sendButton = UIBarButtonItem(title: "test", style: .Plain, target: self, action: #selector(MyClass.test(_:)))
let toolBarItems = [UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: nil),
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil),
sendButton]
Here is the code i tried .
import UIKit
class ViewController2 : UIViewController {
#IBOutlet weak var mytoolbar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad();
let sendButton = UIBarButtonItem(title: "test", style: .Plain, target: self, action: nil)
let toolBarItems = [UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: nil),
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil),
sendButton]
mytoolbar.items = toolBarItems
}
}
Edit : I'm using the below code to create the uitoolbar programmatically.
let mytoolbar = UIToolbar.init(frame: CGRect(x: 0 , y: 0, width:self.view.frame.size.width, height: 44))
mytoolbar.backgroundColor = UIColor.blueColor()
let sendButton = UIBarButtonItem(title: "test", style: .Plain, target: self, action: nil)
let toolBarItems = [UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: nil),
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil),
sendButton]
mytoolbar.items = toolBarItems
self.view.addSubview(mytoolbar)
Hope this helps now
Here are the results:
It is centered i guess . Can you show me your code to add UIToolbar ?

iOS Swift 2.0 Done Button

I'm trying to add a Done button to a keyboard. The code below used to work:
func addDoneButtonOnKeyboard()
{
let doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, screenWidth, 50))
//doneToolbar.barStyle = UIBarStyle.BlackTranslucent
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction"))
var items: [UIBarButtonItem]?
items?.append(flexSpace)
items?.append(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
commentsField.inputAccessoryView=doneToolbar
}
It puts the toolbar above the keyboard but there is no done button.
The issue comes from the line
var items: [UIBarButtonItem]?
Your array of UIBarButtonItem is never initialized. Replace this line with
var items: [UIBarButtonItem]? = [UIBarButtonItem]()

How to add multiple UIBarButtonItems on right side of Navigation Bar?

I would like to have more than a single UIBarButtonItem on the right side of my UINavigationBar. How can I achieve this?
An example of what I am trying are shown below - you can notice that the top right has more than one button.
Use this in swift:
override func viewDidLoad() {
super.viewDidLoad()
let editImage = UIImage(named: "plus")!
let searchImage = UIImage(named: "search")!
let editButton = UIBarButtonItem(image: editImage, style: .Plain, target: self, action: "didTapEditButton:")
let searchButton = UIBarButtonItem(image: searchImage, style: .Plain, target: self, action: "didTapSearchButton:")
navigationItem.rightBarButtonItems = [editButton, searchButton]
}
Write the action functions like this:
func didTapEditButton(sender: AnyObject){
...
}
func didTapSearchButton(sender: AnyObject){
...
}
Swift 4 & 5
override func viewDidLoad() {
super.viewDidLoad()
let editImage = UIImage(named: "edit")!
let searchImage = UIImage(named: "search")!
let editButton = UIBarButtonItem(image: editImage, style: .plain, target: self, action: #selector(didTapEditButton(sender:)))
let searchButton = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(didTapSearchButton(sender:)))
navigationItem.rightBarButtonItems = [editButton, searchButton]
}
#objc func didTapEditButton(sender: AnyObject){
}
#objc func didTapSearchButton(sender: AnyObject){
}
-(void)viewDidLoad{
UIBarButtonItem *anotherButton1 = [[UIBarButtonItem alloc] initWithTitle:#"Button_1" style:UIBarButtonItemStylePlain target:self action:#selector(button_1:)];
UIBarButtonItem *anotherButton2 = [[UIBarButtonItem alloc] initWithTitle:#"Button_" style:UIBarButtonItemStylePlain target:self action:#selector(button_2:)];
self.navigationItem.rightBarButtonItems=#[anotherButton1,anotherButton2];
}
In Swift 3 you can use:
let editImage = UIImage(named: "plus")!
let searchImage = UIImage(named: "search")!
let editButton = UIBarButtonItem(image: editImage, style: .plain, target: self, action: #selector(didTapEditButton))
let searchButton = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(didTapSearchButton))
navigationItem.rightBarButtonItems = [editButton, searchButton]
I think nothing of the above is going to work
Try this
var burgerItem = UIBarButtonItem(image: UIImage(named:"categories"), style: .Plain, target: self, action: "categories")
var weatherItem = UIBarButtonItem(title: "Weather", style: .Plain, target: self, action: "weather")
burgerItem.tintColor = UIColor.whiteColor()
weatherItem.tintColor = UIColor.whiteColor()
navigationItem.setRightBarButtonItems([burgerItem,weatherItem], animated: true)
You have to use navigationItem.setRightBarButtonItems and be carefull. navigationItem has to be of a view controller.
class testViewController:UIViewController {
ovverride func viewDidLoad() {
self.navigationItem.setRightBarButtonItems(...
}
}
Simply add this code:
self.navigationItem.leftBarButtonItem = nil
let button = UIButton(type: .custom)
button.setImage(UIImage (named: "ChatTab"), for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
let button2 = UIButton(type: .custom)
button2.setImage(UIImage (named: "ActivityTab"), for: .normal)
button2.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem2 = UIBarButtonItem(customView: button2)
self.navigationItem.rightBarButtonItems = [barButtonItem, barButtonItem2]
This is the result:
With Swift 4
let editImage = UIImage(named: "toolbar_edit")!
let favoriteImage = UIImage(named: "toolbar_fav_solid")!
let editButton = UIBarButtonItem(image: editImage, style: .plain, target: self, action: #selector(didTapEditButton))
let favoriteButton = UIBarButtonItem(image: favoriteImage, style: .plain, target: self, action: #selector(didTapFavoriteButton))
navigationItem.rightBarButtonItems = [editButton, favoriteButton]
Click action for those buttons
#objc func didTapEditButton(sender: AnyObject) {
print("edit")
}
#objc func didTapFavoriteButton(sender: AnyObject) {
print("favorite")
}
Output screenshot (iPhone X)
Accepted answer as well as few of the answer is absolutely correct but in my case none of them work.
Reason : My View Controller was Inherited from UIViewController and I had to set Add to Cart Button and Search Button On Right hand side. And All my view controllers were a part of UITabbarController.
let editImage = UIImage(named: "OrdersTabIcon")
let searchImage = UIImage(named: "OrdersTabIcon")
let editButton = UIBarButtonItem(image: editImage, style: .plain, target: self, action: #selector(iconTapped))
let searchButton = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(iconTapped))
Instead of using
self.navigationItem.setRightBarButtonItems([editButton, searchButton], animated: true)
Use This .
self.navigationController?.navigationBar.topItem?.setRightBarButtonItems([editButton, searchButton], animated: true)
This is may be help for you in objective-c,
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.navigationItem.title = #"Title";
UIBarButtonItem *logOutButton = [[UIBarButtonItem alloc] initWithTitle:#"Logout" style:UIBarButtonItemStylePlain target:self action:#selector(ButtonClickedAtIndex1:)];
[logOutButton setTintColor:[UIColor blackColor]];
logOutButton.tag = 1;
UIBarButtonItem *syncBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Sync" style:UIBarButtonItemStylePlain target:self action:#selector(ButtonClickedAtIndex1:)];
[syncBarButtonItem setTintColor:[UIColor blackColor]];
syncBarButtonItem.tag = 2;
self.navigationItem.leftBarButtonItem = logOutButton;
self.navigationItem.rightBarButtonItem = syncBarButtonItem;
float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (systemVersion >= 7.0) {
self.edgesForExtendedLayout = UIRectEdgeNone;
self.navigationController.navigationBar.translucent = NO;
}
}
return self;
}
Use navigationItem's rightBarButtonItems, which takes an array of UIBarButton. Appledoc
let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareTapped))
let add = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
navigationItem.rightBarButtonItems = [add, share]
I don't know wether an Interface Builder solution was not possible before, but at least with the most recent update (Xcode 11.0), it is possible to drag two UI Bar Buttons into the rightBarButton space. Two outlets and actions can then be dragged into the code like always.
Since the OP didn't ask for a solution without IB, I think this also qualifies as an answer.
For Xamarin iOS with the new updates, it is like:
UIBarButtonItem Button1 = new UIBarButtonItem(UIImage.FromBundle("Image1"), UIBarButtonItemStyle.Plain,YourEventHandler);
UIBarButtonItem Button2 = new UIBarButtonItem(UIImage.FromBundle("Image1"), UIBarButtonItemStyle.Plain,YourEventHandler);
NavigationItem.SetRightBarButtonItems(new[]{ Button1, Button2 }, true);

Resources