How to change UINavigationBar rightButton image? [duplicate] - ios

This question already has answers here:
Changing the UINavigationBar background image
(7 answers)
Closed 6 years ago.
I want to change UINavigationBar rightButton image in viewWillAppear and for this I'm trying this:
self.navigationController?.navigationItem.rightBarButtonItem?.image = UIImage(named: "bookmark")
but it does not change the image of my rightButton. How can I fix it and change my image?

try this
var changeImage:UIImage = UIImage(named: "bookmark")!
changeImage = changeImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
var rightButton = UIBarButtonItem(image: changeImage, style: UIBarButtonItemStyle.Bordered, target: self, action: "xxxx")
self.navigationItem.rightBarButtonItem = rightButton
Choice-2
for book mark use default function of UIBarButtonSystemItemBookmarks
var rightButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Bookmarks, target: self, action: "xxxx")
self.navigationItem.rightBarButtonItem = rightButton
some default UIBarbuttonItems are
typedef NS_ENUM(NSInteger, UIBarButtonSystemItem) {
UIBarButtonSystemItemDone,
UIBarButtonSystemItemCancel,
UIBarButtonSystemItemEdit,
UIBarButtonSystemItemSave,
UIBarButtonSystemItemAdd,
UIBarButtonSystemItemFlexibleSpace,
UIBarButtonSystemItemFixedSpace,
UIBarButtonSystemItemCompose,
UIBarButtonSystemItemReply,
UIBarButtonSystemItemAction,
UIBarButtonSystemItemOrganize,
UIBarButtonSystemItemBookmarks,
UIBarButtonSystemItemSearch,
UIBarButtonSystemItemRefresh,
UIBarButtonSystemItemStop,
UIBarButtonSystemItemCamera,
UIBarButtonSystemItemTrash,
UIBarButtonSystemItemPlay,
UIBarButtonSystemItemPause,
UIBarButtonSystemItemRewind,
UIBarButtonSystemItemFastForward,
UIBarButtonSystemItemUndo NS_ENUM_AVAILABLE_IOS(3_0),
UIBarButtonSystemItemRedo NS_ENUM_AVAILABLE_IOS(3_0),
UIBarButtonSystemItemPageCurl NS_ENUM_AVAILABLE_IOS(4_0),
};

self.navigationController?.navigationItem.rightBarButtonItem?.image= UIBarButtonItem(image: //Image Name, style: UIBarButtonItemStyle.Plain, target: self, action: //ACTION NAME)

Try this, I am new to swift that's why i've done this code in Objective C.
UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
[btnRight setFrame : CGRectMake(0, 0, 60, 35)];
[btnRight setImage:[UIImage imageNamed:#"prefferedImage"] forState:UIControlStateNormal];
[btnRight addTarget:self action:#selector(defindeActionMethod:) forControlEvents:UIControlEventTouchUpInside];
[btnRight setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
btnRight.imageView.contentMode = UIViewContentModeScaleAspectFit;
btnRight.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
btnRight.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
[rightBarButton setTintColor:[UIColor whiteColor]];
self.navigationItem.rightBarButtonItem = rightBarButton;

Related

UIBarButtonItem disable animation

I have an UIBarButtonItem, which is a non-clickable logo. How do I disable the touch animation for this logo?
I have tried getting at the view:
let view = self.appTitle.performSelector(Selector("view")).takeRetainedValue() as? UIView
view?.userInteractionEnabled = false
but then the app crashes.
The UIBarButtonItem is inside a UiToolbar, created in a storyboard.
This works:
self.appTitle.customView = UIImageView(image: UIImage(named: "footer"))
If you want UIBarButtonItem be don't clicked use
barBtnItem.enabled = false
let transitionOptions: UIViewAnimationOptions = [.TransitionCrossDissolve, .ShowHideTransitionViews]
UIView.transitionWithView(#yourUIBarButtonItem outlet, duration: 1.0, options: transitionOptions, animations: {
self.#yourUIBarButtonItem outlet.enabled = false
}, completion: nil)
If your UIBarButtonItem is in NavigationItem then first assign it to leftBarButtonItem or rightBarButtonItem and then set enabled property of UIBarButtonItem to NO in objective-c and false in swift
Objective-C:
UIImage *menuImage = [UIImage imageNamed:#"menu"];
UIButton *menu = [UIButton buttonWithType:UIButtonTypeCustom];
menu.frame = CGRectMake( 10, 0, menuImage.size.width, menuImage.size.height);
[menu addTarget:self action:#selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
[menu setImage:menuImage forState:UIControlStateNormal];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:menu];
self.navigationItem.leftBarButtonItem = backButton;
self.navigationItem.leftBarButtonItem.enabled = NO;
Swift:
var menuImage: UIImage = UIImage(named: "menu")!
var menu: UIButton = UIButton(type: .Custom)
menu.frame = CGRectMake(10, 0, menuImage.size.width, menuImage.size.height)
menu.addTarget(self, action: #selector(self.handleBack), forControlEvents: .TouchUpInside)
menu.setImage(menuImage, forState: .Normal)
var backButton: UIBarButtonItem = UIBarButtonItem(customView: menu)
self.navigationItem.leftBarButtonItem = backButton
self.navigationItem.leftBarButtonItem.enabled = false

How to change space between UIBarButtonItems in UINavigationBar?

This is how it looks now:
This is how it is represented in Debug view Hierarchy:
And here is how I set it up in code:
func setupUserAndCartButtons() {
var rightBarButtonItems = [UIBarButtonItem]()
let cartBarButtonItem = UIBarButtonItem(image: DBCart.sharedCart().icon, style: .Plain, target: self, action: Selector("cartButtonTapped:"))
rightBarButtonItems.append(cartBarButtonItem)
let userIcon = UIImage(named: "icon-user")
let userBarButtonItem = UIBarButtonItem(image: userIcon, style: .Plain, target: self, action: Selector("userButtonTapped:"))
rightBarButtonItems.append(userBarButtonItem)
navigationItem.rightBarButtonItems = rightBarButtonItems
}
Hot to move them closer to each other without using custom view?
use imageInsets property of UIBarButtonItem
In Objective-C
[addContact setImageInsets:UIEdgeInsetsMake(0, -10,0, 0)];
Swift 4.1
buttonName.imageInsets = UIEdgeInsetsMake(0, 30, 0, 0)
This will move button to right side to other button.
Hope this will help someone
Add buttons using custom View:
//MARK:Customize Navigation Bar
func addButtonsToNavigationBar(){
let cartButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
cartButton.frame = CGRectMake(0,0,20,20)
cartButton.addTarget(self, action: "cartButtonTapped:", forControlEvents: .TouchUpInside)
cartButton.setImage(UIImage(named: DBCart.sharedCart().icon), forState: .Normal)
let cartBarButtonItem = UIBarButtonItem(customView: cartButton)
let userButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
userButton.frame = CGRectMake(0,0,20,20)
userButton.addTarget(self, action: "userButtonTapped:", forControlEvents: .TouchUpInside)
userButton.setImage(UIImage(named: "icon-user"), forState: .Normal)
let userBarButtonItem = UIBarButtonItem(customView: userButton)
self.navigationItem.rightBarButtonItems=[cartBarButtonItem,userBarButtonItem]
}
UIBarButtonSystemItemFixedSpace is used to adjust spacings of navigation bar items.
Example code:
- (void)setRightBarButtonItems {
UIBarButtonItem *addTaskButton =
[[UIBarButtonItem alloc] bk_initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
handler:handler];
UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
if ([UIDevice isIOS7Plus]) {
negativeSeperator.width = -12;
} else {
negativeSeperator.width = -8;
}
UIBarButtonItem *separator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
separator.width = 50;
[self.navigationItem setRightBarButtonItems:#[addTaskButton, separator, [self filterButton]]];
}

How to set Navigation back button icon in all view controller like globally?

I can perform operation to set navigation back button icon on all the views commonly. For example if I put code in App Delegate method then it's used for all the controllers.
Here is The final Answer which i have used in my current App hope it will useful..
in view DidLoad method..
UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
leftButton.frame = CGRectMake(0, 0, 40, 40);
[leftButton setImage:[UIImage imageNamed:#"Back"] forState:UIControlStateNormal];
[leftButton addTarget:self action:#selector(left_menu_click:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
self.navigationItem.leftBarButtonItem = leftBarButtonItem;
add this method for navigate popViewController..
-(IBAction)left_menu_click:(id)sender{
[self.navigationController popViewControllerAnimated:YES];
}
You may try below appearance with correct image for back button throughout app.
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:#"back_button_bg"]
forState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
You may try custom button like this:
+ (UIBarButtonItem *)backButtonForTarget:(id)target
{
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:target action:#selector(back) forControlEvents:UIControlEventTouchUpInside];
[btn setFrame:CGRectMake(0, 0, 70, 44)];
[btn setImageEdgeInsets:UIEdgeInsetsMake(11, -10, 8, 35)];
[btn setImage:[UIImage imageNamed:#"topbar_back.png"] forState:UIControlStateNormal];
UIBarButtonItem *barbtnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
return barbtnItem;
}
add this button as leftBarButtonItem
self.navigationItem.leftBarButtonItem = [UtilityClass backButtonForTarget:self];
Add following code in didFinishLaunchingWithOptions method in AppDelegate class :
// Following line is for tint color that is optional, You can add if you wants to change color of back button
[[UIBarButtonItem appearance] setTintColor:[UIColor redColor]];
If you want change background images then
// Change the appearance of back button
UIImage *backButtonImage = [[UIImage imageNamed:#"button_back"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 6)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
Just found a solution using appearance()
Swift
let backImage = UIImage(named: "back")
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:
UIColor.white], for: .normal)
UIBarButtonItem.appearance().tintColor = UIColor.green
You should modify UINavigationBar like:
let appearance = UINavigationBar.appearance()
appearance.backIndicatorImage = image
appearance.backIndicatorTransitionMaskImage = image
If you want to remove default title, you add:
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
to view controller that pushes to the navigation controller.
You can find more on Apple docs
You can try this
let backImage = UIImage(named: "icon")
let backImageUIEdgeInsets = UIEdgeInsets(top: -4, left: -8, bottom: -2, right: 8)
let backImageWithAlignmentRectInsets = backImage?.withAlignmentRectInsets(backImageUIEdgeInsets)
appearance.setBackButtonBackgroundVerticalPositionAdjustment(-1.0, for: .default)
appearance.setBackButtonBackgroundImage(backImageWithAlignmentRectInsets,
for: .normal,
barMetrics: .default)
appearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear],
for: .normal)
appearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear],
for: .highlighted)

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

How can I add a toolbar above the keyboard?

I have created a UIToolBar programmatically and added a UITextField on it. Now, I need that toolbar to be above the keyboard when I click in another text field.
UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0,400, 320, 60)];
[self.view addSubview:toolBar];
UITextField *txtView=[[UITextField alloc]initWithFrame:CGRectMake(0, 400, 260, 30)];
txtView.backgroundColor =[UIColor grayColor];
txtView.placeholder=#"Address";
UIBarButtonItem *txtfieldItem=[[UIBarButtonItem alloc]initWithCustomView:txtView];
toolBar.items =[NSArray arrayWithObject:txtfieldItem];
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
}
You do not need to do this in code anymore.
Just simply drag UIView to the top bar of current scene and customize it as you want.
In code simply put IBOutlet for both: toolbarView and textView and make connections.
#IBOutlet private var toolbarView: UIView!
#IBOutlet private var textView: UITextView!
In viewDidLoad setup your toolbarView as accessoryView of your UItextView.
override func viewDidLoad() {
super.viewDidLoad()
textView.inputAccessoryView = toolbarView
}
The result is following:
For swift (1.2):
let numberToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
numberToolbar.barStyle = UIBarStyle.Default
numberToolbar.items = [
UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "keyboardCancelButtonTapped:"),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "keyboardDoneButtonTapped:")]
numberToolbar.sizeToFit()
yourTextView.inputAccessoryView = numberToolbar
You Can Use this code it work for me.
-(void)viewdidload
{
UIToolbar* keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:#"Done"
style:UIBarButtonItemStyleBordered target:self
action:#selector(doneClicked:)];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
textField.inputAccessoryView = keyboardDoneButtonView;
}
-(void)doneClicked:(id)sender
{
NSLog(#"Done Clicked.");
[self.view endEditing:YES];
}
You can use the UITextFields inputAccessoryView property
txtField.inputAccessoryView = toolBar;
Swift 3
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
toolBar.barStyle = UIBarStyle.default
toolBar.items = [
UIBarButtonItem(title: "Button1", style: UIBarButtonItemStyle.plain, target: self, action: #selector(test2)),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Button2", style: UIBarButtonItemStyle.plain, target: self, action: #selector(test1))]
toolBar.sizeToFit()
myTextField.inputAccessoryView = toolBar
Swift 5.0 and above
let toolBar = UIToolbar(frame: CGRect(x: 0.0,
y: 0.0,
width: UIScreen.main.bounds.size.width,
height: 44.0))//1
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)//2
let DoneButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: #selector(tapDone))//3
toolBar.setItems([flexibleSpace, DoneButton], animated: false)
textField.inputAccessoryView = toolBar
// Done Action
#objc func tapDone() {
self.view.endEditing(true)
}
textField.inputAccessoryView=[weakSelf addToolBar];
[textField setKeyboardType:UIKeyboardTypeNumberPad];
and add a method
-(UIToolbar *)addToolBar
{
UIBarButtonItem *done=[[UIBarButtonItem alloc]initWithTitle:#"DONE" style:UIBarButtonItemStyleDone target:self action:#selector(done:)];
UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
NSArray* toolBarItems=[[NSArray alloc]initWithObjects:done, nil];
[toolBar setItems:toolBarItems];
return toolBar;
}
In Swift 3 and 4
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.isUserInteractionEnabled = true
toolBar.sizeToFit()
toolBar.items = [
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.sendCodeBtnAction(sender:)))]
tfPhone.inputAccessoryView = toolBar

Resources