How can I add a toolbar above the keyboard? - ios

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

Related

How to add background Image to a UIBarButtonItem

I have the following code that adds a UIToolbar on the top of the keyboard when a textField is tapped.
How can I add a background image to one of the buttons?
I tried...
toolBar.items![1].setBackButtonBackgroundImage(clearButton, forState:.Normal, barMetrics:.Default)
but it didn't work, I get error...
Use of unresolved identifier 'imageName'
Code:
func addButtonsToKeyboard(){
let toolBar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
toolBar.barStyle = UIBarStyle.Default
toolBar.tintColor = UIColor.blueColor()
toolBar.barTintColor = UIColor.grayColor()
toolBar.items = [
UIBarButtonItem(title: "Button1", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(someFunction)),
UIBarButtonItem(title: "Button2", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(someFunction)),
UIBarButtonItem(title: "Button3", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(someFunction))]
toolBar.sizeToFit()
toolBar.items![1].setBackButtonBackgroundImage(myImage, forState:.Normal, barMetrics:.Default)
myTextField.inputAccessoryView = toolBar
}
BTW - The image myImage is located in Assets.xcassets.
Perhaps you could try to create a UIImage variable, and then pass that in just to be more explicit:
var myImage = UIImage(named: "myImage")
toolBar.items![1].setBackButtonBackgroundImage(myImage, forState:.Normal, barMetrics:.Default)

How to add done button on keyboard on top of keyboard in IOS?

I want to add the Done button on the top of keyboard on right side in iOS for a textView.Please tell me how can i do that?
I want to achieve something similar to the above keyboard
Hope this help :)
UIToolbar* keyboardToolbar = [[UIToolbar alloc] init];
[keyboardToolbar sizeToFit];
UIBarButtonItem *flexBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(yourTextViewDoneButtonPressed)];
keyboardToolbar.items = #[flexBarButton, doneBarButton];
self.yourTextView.inputAccessoryView = keyboardToolbar;
and then add yourTextViewDoneButtonPressed method
-(void)yourTextViewDoneButtonPressed
{
[self.yourTextView resignFirstResponder];
}
It can be done using storyboard:
Add UITextField to UIViewController view.
Add UIToolbar in the first level of UIViewController
Add UIBarButtonItem into the UIToolbar.
Connect UItoolbar to the code using IBOutlet.
Connect UIBarButtonItem to the code using IBAction (as didClick).
Make the UITextField will be delegating to UIViewController.
In the didClick function end editing (view.endEditing(true))
In the delegate function textFieldShouldBeginEditing should be: textField.inputAccessoryView = toolbar and returns true.
Swift 3:
func setDoneOnKeyboard() {
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(InsertStatusVC.dismissKeyboard))
keyboardToolbar.items = [flexBarButton, doneBarButton]
self.fullNameTextField.inputAccessoryView = keyboardToolbar
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
This Solution For Swift3+
Add This line To your Project As a extension
Your Problem is solved.
extension UITextField{
#IBInspectable var doneAccessory: Bool{
get{
return self.doneAccessory
}
set (hasDone) {
if hasDone{
addDoneButtonOnKeyboard()
}
}
}
func addDoneButtonOnKeyboard()
{
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
#objc func doneButtonAction() {
self.resignFirstResponder()
}
}
Before extension
After extension
Solution for Swift 4 and Swift 5 using a custom class. You can use this class in your Storyboard and .xib files.
class UITextFieldWithDoneButton: UITextField {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addDoneButtonOnKeyboard()
}
fileprivate func addDoneButtonOnKeyboard() {
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
#objc fileprivate func doneButtonAction() {
self.resignFirstResponder()
}
}
This Solution For Swift 4
override func viewDidLoad() {
super.viewDidLoad()
//init toolbar
let toolbar:UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 30))
//create left side empty space so that done button set on right side
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBtn: UIBarButtonItem = UIBarButtonItem(title: “Done”, style: .done, target: self, action: Selector(“doneButtonAction”))
toolbar.setItems([flexSpace, doneBtn], animated: false)
toolbar.sizeToFit()
//setting toolbar as inputAccessoryView
self.textField1.inputAccessoryView = toolbar
self.textField2.inputAccessoryView = toolbar
}
func doneButtonAction() {
self.view.endEditing(true)
}
Add UIToolBar as custom view that will have UIBarButtonItem as Done button in it.
This is safer and cleaner way to add Done button to any Type of Keyboard. Create UIToolBar add Done Button to it and set inputAccessoryView of any UITextField or UITextView.
];
}
SWIFT 3
var ViewForDoneButtonOnKeyboard = UIToolbar()
ViewForDoneButtonOnKeyboard.sizeToFit()
var btnDoneOnKeyboard = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneBtnFromKeyboardClicked))
ViewForDoneButtonOnKeyboard.items = [btnDoneOnKeyboard]
myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard
Function
#IBAction func doneBtnfromKeyboardClicked (sender: Any) {
print("Done Button Clicked.")
//Hide Keyboard by endEditing or Anything you want.
self.view.endEditing(true)
}
The answer from Ramis that allows the keyboard accessory view to be created using the Storyboard is a great strategy. It is 2017 after all! (Sorry, but I do not have enough points to upvote you.)
Let me add a little to the answer (to keep within the SO rules). I have a view with multiple textFields. After implementing each of Ramis' steps I attached the accessoryView to all of the textFields in this way:
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
_activeTextField = textField;
[_activeTextField setInputAccessoryView:_iboKeyboardTools];
}
So easy compared with implementing all this in code! Just build the accessory view in Storyboard- and attach it again and again!

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

UIBarButtonItem not clickable in UIToolBar

I have a UIPickerView and I am adding a UIToolBar with 2 UIBarButtonItems to it.
var toolBar = UIToolbar()
toolBar.frame.origin.y = -40
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePicker")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "canclePicker")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
pickerView.addSubview(toolBar)
pickerView.bringSubviewToFront(toolBar)
view.bringSubviewToFront(toolBar)
The problem is, that when I try to click on the the UIBarButtonItem, it doesn't fire, it doesn't even recognize it, it just clicks the cell beneath it.
Can you try this codes.
var textField = UITextField(frame: CGRectMake(20, 50, view.width - 40, 30))
textField.backgroundColor = UIColor.redColor()
view.addSubview(textField)
var pickerView = UIPickerView(frame: CGRectMake(0, 200, view.width, 300))
pickerView.backgroundColor = UIColor.whiteColor()
pickerView.showsSelectionIndicator = true
var toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePicker")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "canclePicker")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
textField.inputView = pickerView
textField.inputAccessoryView = toolBar
I believe that you need to raise the picker and toolbar using the standard UIResponder mechanism or cheat by using a hidden UITextField to get the same result.
See my updated answer to your original question:
Add buttons to UIPickerView - Swift 1.2

Resources