"Done" UIBarButtonItem not displaying on number pad (Swift) - ios

I'm trying to add a "Done" button to a text field.
The black UIToolbar is displaying, but the "Done" button is not.
In the attributes inspector, 'Return key' is set to 'Done' and 'Auto-enable Return Key' is enabled.
The UITextField is connected to the delegate
This is inside a UITableViewCell:
import UIKit
class itemTableViewCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet var itemName: UILabel!
#IBOutlet var itemInput: UITextField!
var textFieldIsBeingEdited: Bool = false
override func awakeFromNib() {
super.awakeFromNib()
itemInput.delegate = self
self.addDoneButtonToKeyboard()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func addDoneButtonToKeyboard(){
let doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 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: itemInput, action: Selector("doneButtonAction"))
let items = NSMutableArray()
items.addObject(flexSpace)
items.addObject(done)
doneToolbar.sizeToFit()
itemInput.inputAccessoryView = doneToolbar
}
func doneButtonAction()
{
self.itemInput.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
}

you forget to add the items to your let doneToolbar: UIToolbar
doneToolbar.items = items as [AnyObject]
brief answer
items.addObject(flexSpace)
items.addObject(done)
doneToolbar.items = items as [AnyObject]
doneToolbar.sizeToFit()
itemInput.inputAccessoryView = doneToolbar

Related

Subclassing UITextField to include a picker and a toolbar

Problem
I have an application that has a user registration view. It has many UITextField, and many of these have a picker with a toolbar embedded to close the picker i.e:
myTextField.inputView = myPicker
myTextField.inputAccessoryView = myToolbar
Essentially I want to reuse these text fields in different parts of my application, so I thought of subclassing UITextField, something like PickerUITextField.
Attempt
I've tried something like this:
class PickerUITextField: UITextField {
let picker = UIPickerView()
let toolbar = UIToolbar()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
withToolbar()
self.inputView = self.picker
self.inputAccessoryView = self.toolbar
}
private func withToolbar() {
toolbar.barStyle = UIBarStyle.default
toolbar.isTranslucent = true
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: .done,
target: self, action: #selector(removeToolBar))
toolbar.setItems([space, doneButton], animated: false)
toolbar.isUserInteractionEnabled = true
toolbar.sizeToFit()
}
#objc func removeToolBar() {
self.resignFirstResponder()
}
}
Question
However, how can I detect in the view controller that the user has pressed the "Done" button of my PickerUITextField? In other words:
class UserRegistrationViewController: UIViewController {
#IBOutlet weak var country: PickerUITextField!
// I want this to be triggered whenever the country picker closes
func didSelectCountry() {
print("User selected \(country.text!)")
}
}
Thank you for the help.
You can create a closure in PickerUITextField to perform done button action.
class PickerUITextField: UITextField {
let picker = UIPickerView()
let toolbar = UIToolbar()
var doneBtnAction:(() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
withToolbar()
self.inputView = self.picker
self.inputAccessoryView = self.toolbar
}
private func withToolbar() {
toolbar.barStyle = UIBarStyle.default
toolbar.isTranslucent = true
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: .done,
target: self, action: #selector(removeToolBar))
toolbar.setItems([space, doneButton], animated: false)
toolbar.isUserInteractionEnabled = true
toolbar.sizeToFit()
}
#objc func removeToolBar() {
doneBtnAction?()
self.resignFirstResponder()
}
}
And in your view controller, you can assign a closure. It will be called when you tap the done button.
class UserRegistrationViewController: UIViewController {
#IBOutlet weak var country: PickerUITextField!
override func viewDidLoad() {
super.viewDidLoad()
country.doneBtnAction = { [weak self] in
print("User selected \(self?.country.text!)")
}
}
}
You can use a protocol/delegate:
protocol PickerUITextFieldDelegate: class {
func didSelectCountry()
}
class PickerUITextField: UITextField {
// UITextField already have a 'delegate' we need a different name
weak var pickerDelegate: PickerUITextFieldDelegate?
let picker = UIPickerView()
let toolbar = UIToolbar()
#objc func removeToolBar() {
self.resignFirstResponder()
self.pickerDelegate?.didSelectCountry()
}
}
// We need to implement the PickerUITextFieldDelegate delegate here:
class UserRegistrationViewController: UIViewController, PickerUITextFieldDelegate {
#IBOutlet weak var country: PickerUITextField!
// Don't forget to set the delegate!
override func viewDidLoad() {
super.viewDidLoad()
self.country.pickerDelegate = self
}
// This will now be triggered by the delegate
func didSelectCountry() {
print("User selected \(country.text!)")
}
}

Why #selector doesn't call handler method for iPad's keyboard shortcuts?

I have a class for constructing UIBarButtonItems:
enum KeyboardToolbarButton: Int {
case done = 0
case cancel
case back, backDisabled
case forward, forwardDisabled
func createButton(target: Any?, action: Selector?) -> UIBarButtonItem {
var button: UIBarButtonItem!
switch self {
case .back:
button = UIBarButtonItem(title: "<=", style: .plain, target: target, action: action)
case .backDisabled:
button = UIBarButtonItem(title: "<=", style: .plain, target: target, action: action)
button.isEnabled = false
case .forward:
button = UIBarButtonItem(title: "=>", style: .plain, target: target, action: action)
case .forwardDisabled:
button = UIBarButtonItem(title: "=>", style: .plain, target: target, action: action)
button.isEnabled = false
case .done:
button = UIBarButtonItem(title: "DONE", style: .plain, target: target, action: action)
case .cancel:
button = UIBarButtonItem(title: "CANCEL", style: .plain, target: target, action: action)
}
button.tag = rawValue
return button
}
static func detectType(barButton: UIBarButtonItem) -> KeyboardToolbarButton? {
return KeyboardToolbarButton(rawValue: barButton.tag)
}
}
Class for constructing KeyboardToolbar from KeyboardToolbarButton:
class KeyboardToolbar {
weak var toolBarDelegate: KeyboardToolbarDelegate?
var textField: UITextField!
init(textField: UITextField) {
self.textField = textField
self.textField.autocorrectionType = .no
self.textField.inputAssistantItem.leadingBarButtonGroups = []
self.textField.inputAssistantItem.trailingBarButtonGroups = []
}
func setup(leftButtons: [KeyboardToolbarButton], rightButtons: [KeyboardToolbarButton]) {
let leftBarButtons = leftButtons.map { (item) -> UIBarButtonItem in
return item.createButton(target: self, action: #selector(self.buttonTapped(sender:)))
}
let rightBarButtons = rightButtons.map { (item) -> UIBarButtonItem in
return item.createButton(target: self, action: #selector(self.buttonTapped(sender:)))
}
let groupLeading: UIBarButtonItemGroup = UIBarButtonItemGroup.init(barButtonItems: leftBarButtons, representativeItem: nil)
let groupTrailing: UIBarButtonItemGroup = UIBarButtonItemGroup.init(barButtonItems: rightBarButtons, representativeItem: nil)
textField.inputAssistantItem.leadingBarButtonGroups.append(groupLeading)
textField.inputAssistantItem.trailingBarButtonGroups.append(groupTrailing)
}
#objc func buttonTapped(sender: UIBarButtonItem) {
if let type = KeyboardToolbarButton.detectType(barButton: sender) {
print(type)
toolBarDelegate?.keyboardToolbar(button: sender, type: type, tappedIn: self)
}
}
}
And delegate:
protocol KeyboardToolbarDelegate: class {
func keyboardToolbar(button: UIBarButtonItem, type: KeyboardToolbarButton, tappedIn toolbar: KeyboardToolbar)
}
Here's how I use KeyboardToolbar:
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
addButtons(for: textField, setLeftButtons: [.back, .forward], andRightButtons: [.done])
}
private func addButtons(for textField: UITextField, setLeftButtons leftButtons: [KeyboardToolbarButton] = [], andRightButtons rightButtons: [KeyboardToolbarButton] = []) {
let toolbar = KeyboardToolbar(textField: textField)
toolbar.toolBarDelegate = self
toolbar.setup(leftButtons: leftButtons, rightButtons: rightButtons)
}
}
extension ViewController: KeyboardToolbarDelegate {
func keyboardToolbar(button: UIBarButtonItem, type: KeyboardToolbarButton, tappedIn toolbar: KeyboardToolbar) {
print("Tapped button type: \(type)")
}
}
Here's how it works (this feature available only on iPad)
So, the problem is that #objc func buttonTapped(sender: UIBarButtonItem) never calls. So, #selector(self.buttonTapped(sender:) does not connect to handler. How to fix it?
Update:
According to the answer of Taras Chernyshenko, I added KeyboardToolbar as a member of ViewController:
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
var toolbar: KeyboardToolbar!
override func viewDidLoad() {
super.viewDidLoad()
addButtons(for: textField, setLeftButtons: [.back, .forward], andRightButtons: [.done])
}
private func addButtons(for textField: UITextField, setLeftButtons leftButtons: [KeyboardToolbarButton] = [], andRightButtons rightButtons: [KeyboardToolbarButton] = []) {
toolbar = KeyboardToolbar(textField: textField)
toolbar.toolBarDelegate = self
toolbar.setup(leftButtons: leftButtons, rightButtons: rightButtons)
}
}
Problem is in you design. In KeyboardToolbar class in func setup(leftButtons:, rightButtons:) function you doing next:
let leftBarButtons = leftButtons.map { (item) -> UIBarButtonItem in
return item.createButton(target: self, action: #selector(self.buttonTapped(sender:)))
}
here you are setting action target to KeyboardToolbar class.
Next in addButtons(for textField:, setLeftButtons leftButtons:, andRightButtons rightButtons:) of ViewController you setup your buttons like
let toolbar = KeyboardToolbar(textField: textField)
toolbar.toolBarDelegate = self
toolbar.setup(leftButtons: leftButtons, rightButtons: rightButtons)
but after this function toolbar is dealocated, so actions can't reach their target.
To simple fix, store toolbar into class property
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
var toolbar = KeyboardToolbar?
override func viewDidLoad() {
super.viewDidLoad()
addButtons(for: textField, setLeftButtons: [.back, .forward], andRightButtons: [.done])
}
private func addButtons(for textField: UITextField, setLeftButtons leftButtons: [KeyboardToolbarButton] = [], andRightButtons rightButtons: [KeyboardToolbarButton] = []) {
let toolbar = KeyboardToolbar(textField: textField)
toolbar.toolBarDelegate = self
toolbar.setup(leftButtons: leftButtons, rightButtons: rightButtons)
self.toolbar = toolbar
}
}

How to add buttons above keyboard

How to add button above the keyboard like this one in Stack Exchange app? And when you long press the text in UITextView How to add "Select" and "Select All"?
The first question, you can set textField's inputAccessoryView to your custom view, this can customize the keyboard's header.
The result:
You can do it like below;
first, you should instance the view you want to add above the keyboard.
class ViewController : UIViewController {
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.inputAccessoryView = Bundle.main.loadNibNamed("CustomAccessoryView", owner: self, options: nil)?.first as! UIView?
In your CustomAccessoryView, you can set the action of the button:
import UIKit
class CustomAccessoryView: UIView {
#IBAction func clickLoveButton(_ sender: UIButton) {
print("Love button clicked")
}
}
I would recommend to create a toolbar for your UITextField's accessoryView property.
The idea is to add this toolbar once, before the textfield would show for the first time. Therefore, we assign the delegate to self, and override the textFieldShouldBeginEditing delegate call with our implementation to add the accessoryView.
Here is a simple example, how can u achieve it:
import UIKit
class ViewController: UIViewController {
// your `UITextfield` instance
// Don't forget to attach it from the IB or create it programmaticly
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Assign the delegate to self
textField.delegate = self
}
}
// MARK: Create extension to conform to UITextfieldDelegate
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
setupTextFieldsAccessoryView()
return true
}
func setupTextFieldsAccessoryView() {
guard textField.inputAccessoryView == nil else {
print("textfields accessory view already set up")
return
}
// Create toolBar
let toolBar: UIToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
toolBar.barStyle = UIBarStyle.black
toolBar.isTranslucent = false
// Add buttons as `UIBarButtonItem` to toolbar
// First add some space to the left hand side, so your button is not on the edge of the screen
let flexsibleSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) // flexible space to add left end side
// Create your first visible button
let doneButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(didPressDoneButton))
// Note, that we declared the `didPressDoneButton` to be called, when Done button has been pressed
toolBar.items = [flexsibleSpace, doneButton]
// Assing toolbar as inputAccessoryView
textField.inputAccessoryView = toolBar
}
func didPressDoneButton(button: UIButton) {
// Button has been pressed
// Process the containment of the textfield or whatever
// Hide keyboard
textField.resignFirstResponder()
}
}
This should be your output:
You'll have to use the inputAccessoryView of your textfield.
you can put the code snippet below in your viewDidLoad():
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 60))
button.backgroundColor = UIColor.blue
button.setTitle("NEXT", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.addTarget(self, action: #selector(self. yourButton), for: .touchUpInside)
numtextField.inputAccessoryView = button
}
#objc func nextButton()
{
print("do something")
}
Just copy and paste simple code for you accessory button embedded with keypad
func addKeyboardToolbar() {
let ViewForDoneButtonOnKeyboard = UIToolbar()
ViewForDoneButtonOnKeyboard.sizeToFit()
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "login-logo"), for: UIControlState.normal)
button.addTarget(self, action:#selector(doneBtnfromKeyboardClicked), for:.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width:UIScreen.main.bounds.width, height: 30) //CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem.init(customView: button)
ViewForDoneButtonOnKeyboard.items = [barButton]
postTextView.inputAccessoryView = ViewForDoneButtonOnKeyboard
}
func doneBtnfromKeyboardClicked (){
self.contentView.endEditing(true)
}
to add a toolbar with a done button which dismisses the keyboard above a UITextField you can write a UITextField extension with the following function:
public func addAccessoryView() {
let doneButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "resignFirstResponder")
let flexSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
let toolbar = UIToolbar()
toolbar.barStyle = UIBarStyle.Default
toolbar.translucent = true
toolbar.tintColor = Color.blue
toolbar.sizeToFit()
toolbar.setItems([flexSpace, doneButton], animated: false)
toolbar.userInteractionEnabled = true
self.inputAccessoryView = toolbar
}
you can then call the function in your textfield like this:
textfield.addAccessoryView()

Why does my code not add a tool bar and a done button to my keyboards?

I followed a tutorial online to add a custom toolbar and a done button to a keyboard. Xcode does not give me any errors, but when I run my app, there is no toolbar or done button an my keyboard. What did I do wrong in my code? Thanks!
Here is my code-
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
let keyboardDoneButtonShow = UIToolbar(frame: CGRectMake(200,200, self.view.frame.size.width,30))
keyboardDoneButtonShow.barStyle = UIBarStyle .BlackTranslucent
let button: UIButton = UIButton()
button.frame = CGRectMake(0, 0, 65, 20)
button.setTitle("Done", forState: UIControlState .Normal)
button.addTarget(self, action: Selector("textFieldShouldReturn:"), forControlEvents: UIControlEvents .TouchUpInside)
button.backgroundColor = UIColor .clearColor()
let doneButton: UIBarButtonItem = UIBarButtonItem()
doneButton.customView = button
let negativeSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpace.width = -10.0
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let toolbarButton = [flexSpace,doneButton,negativeSpace]
keyboardDoneButtonShow.setItems(toolbarButton, animated: false)
textField.inputAccessoryView = keyboardDoneButtonShow
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
Here is my result-
I think you have not set your TextField's delegate to your View Controller. In viewDidLoad add the following:
self.textField.delegate = self

multiple UIDatePicker one uitextfield

In my ViewController there are several UiTextfield.
I intend to use a single UIDatePicker that is expected to respond accordingly.
my code only responds to event generated by second textfield and not the first one.
I just need to determine which UITextField has generated the event...
import UIKit
class ViewController: UIViewController , UITextFieldDelegate {
var datePicker = UIDatePicker()
#IBOutlet weak var tvDueDate: UITextField!
#IBOutlet weak var tvOtherDate: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//setupDatePicker()
self.tvDueDate.tag = 0
self.tvOtherDate.tag = 1
//setupDatePicker(textField)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldDidEndEditing(textField: UITextField) {
setupDatePicker(textField)
}
func textFieldDidBeginEditing(textField: UITextField) {
setupDatePicker(textField)
}
func setupDatePicker(text: UITextField) {
// Sets up the "button"
//tvDueDate.text = "Pick a due date"
//tvDueDate.textAlignment = .Center
// Removes the indicator of the UITextField
//tvDueDate.tintColor = UIColor.clearColor()
// Specifies intput type
datePicker.datePickerMode = .Date
// Creates the toolbar
let toolBar = UIToolbar()
toolBar.barStyle = .Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()
// Adds the buttons
var doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "doneClick")
var spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelClick")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
// Adds the toolbar to the view
if text.tag == 0{
self.tvDueDate.inputView = datePicker
self.tvDueDate.inputAccessoryView = toolBar
}
else
{
self.tvOtherDate.inputView = datePicker
self.tvOtherDate.inputAccessoryView = toolBar
}
}
func doneClick() {
var dateFormatter = NSDateFormatter()
//dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.dateStyle = .ShortStyle
if tvDueDate.isFirstResponder(){
tvDueDate.text = dateFormatter.stringFromDate(datePicker.date)
tvDueDate.resignFirstResponder()
}else{
tvOtherDate.text = dateFormatter.stringFromDate(datePicker.date)
tvOtherDate.resignFirstResponder()
}
}
func cancelClick() {
if tvDueDate.isFirstResponder(){
tvDueDate.resignFirstResponder()
}else{
tvOtherDate.resignFirstResponder()
}
}
}
Give unique tags to your UITextFields and use UITextField delegates.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//setupDatePicker()
self.tvDueDate.tag = 0
self.tvOtherDate.tag = 1
self.tvDueDate.delegate = self
self.tvOtherDate.delegate = self
//setupDatePicker(textField)
}
// UITextField Delegates
func textFieldDidBeginEditing(textField: UITextField) {
println("TextField did begin editing method called")
if textField.tag == 0
..........
if textField.tag == 2
....
}
func textFieldDidEndEditing(textField: UITextField) {
println("TextField did end editing method called")
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
println("TextField should begin editing method called")
return true;
}
You are calling
setupDatePicker()
From viewDidLoad and your code is
if tvDueDate.isFirstResponder(){
tvDueDate.inputView = datePicker
tvDueDate.inputAccessoryView = toolBar
}
else
{
tvOtherDate.inputView = datePicker
tvOtherDate.inputAccessoryView = toolBar
}
adds picker as inputAccessoryView . As at the point of viewDidLoad no text field is FirstResponder that's why only your else part is excited and its only added to tvOtherDate field.
I would recommend to call it from the textfield delegate method (will begin editing or didbegineditting) or call it on tap. And to check from which it is called also pass the textfield or you can use tag.
Adding Delegates and tags to my UiTextField helped me.......
import UIKit
class ViewController: UIViewController , UITextFieldDelegate {
var datePicker = UIDatePicker()
#IBOutlet weak var tvDueDate: UITextField!
#IBOutlet weak var tvOtherDate: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//setupDatePicker()
self.tvDueDate.tag = 0
self.tvOtherDate.tag = 1
//setupDatePicker(textField)
self.tvDueDate.delegate = self
self.tvOtherDate.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldDidEndEditing(textField: UITextField) {
setupDatePicker(textField)
}
func textFieldDidBeginEditing(textField: UITextField) {
setupDatePicker(textField)
}
func setupDatePicker(text: UITextField) {
// Sets up the "button"
//tvDueDate.text = "Pick a due date"
//tvDueDate.textAlignment = .Center
// Removes the indicator of the UITextField
//tvDueDate.tintColor = UIColor.clearColor()
// Specifies intput type
datePicker.datePickerMode = .Date
// Creates the toolbar
let toolBar = UIToolbar()
toolBar.barStyle = .Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()
// Adds the buttons
var doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "doneClick")
var spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelClick")
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
// Adds the toolbar to the view
if text.tag == 0{
self.tvDueDate.inputView = datePicker
self.tvDueDate.inputAccessoryView = toolBar
}
else
{
self.tvOtherDate.inputView = datePicker
self.tvOtherDate.inputAccessoryView = toolBar
}
}
func doneClick() {
var dateFormatter = NSDateFormatter()
//dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.dateStyle = .ShortStyle
if tvDueDate.isFirstResponder(){
tvDueDate.text = dateFormatter.stringFromDate(datePicker.date)
tvDueDate.resignFirstResponder()
}else{
tvOtherDate.text = dateFormatter.stringFromDate(datePicker.date)
tvOtherDate.resignFirstResponder()
}
}
func cancelClick() {
if tvDueDate.isFirstResponder(){
tvDueDate.resignFirstResponder()
}else{
tvOtherDate.resignFirstResponder()
}
}
}

Resources