ToolBar done button action does not work on UIDatePicker - ios

I set done and cancel button on my UIDatePicker within a toolbar programmatically. However, I could not detect click actions for done and cancel buttons. I could not find the cause of the issue. Here is my code:
#IBAction func btnDueDate_Click(sender: UIButton)
{
var toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("Done_Click"))
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("Cancel_Click"))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
self.datePicker.addSubview(toolBar)
self.datePicker.hidden = false
}
func Done_Click()
{
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
self.btnDueDate.setTitle(dateFormatter.stringFromDate(self.datePicker.date), forState: UIControlState.Normal)
}
func Cancel_Click()
{
self.datePicker.hidden = true
}
Could you help me about what am I doing wrong ?
Thank you for your answers
Best regards
Solved: Thank u for your help, I've solved the problem by editting the code line below:
self.view.addSubview(toolBar)
When I add the toolbar as a subview of self.view, not as a subview of self.datePicker, It works fine.

The reason why your code isn't working is because the UIToolbar is overlapping the UIDatePicker and the picker is receiving all of the inputs.
I would suggest for you to use the property inputAccessoryView and assign the toolbar to this, but unfortunately, this is a read-only property for both the UIButton and UIDatePicker
A work-around which many people are using is to use a UITextField and set the inputView to a UIDatePicker and the inputAccessoryView to a UIToolbar. I've made a small example underneath that you can try out.
//
// ViewController.swift
// DatePickerWithToolbar
//
// Created by Stefan Veis Pennerup on 10/06/15.
// Copyright (c) 2015 Kumuluzz. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tvDueDate: UITextField!
var datePicker = UIDatePicker()
override func viewDidLoad() {
setupDatePicker()
}
func setupDatePicker() {
// 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
tvDueDate.inputView = datePicker
tvDueDate.inputAccessoryView = toolBar
}
func doneClick() {
var dateFormatter = NSDateFormatter()
//dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.dateStyle = .ShortStyle
tvDueDate.text = dateFormatter.stringFromDate(datePicker.date)
tvDueDate.resignFirstResponder()
}
func cancelClick() {
tvDueDate.resignFirstResponder()
}
}

dateFormatter.dateStyle = .ShortStyle
dateFormatter.dateFormat = "dd-MM-yyyy"
Note : to function dateformat under datesyle

Showing UIDatePicker when UIButton pressed with Done button from this answer
var datePickerContainer = UIView()
let timePicker = UIDatePicker()
#IBAction func openTimePicker(sender: UIButton) {
datePickerContainer.frame = CGRect(x: 0.0, y: (self.view.frame.height/2 + 30), width: self.view.frame.width, height: 250)
datePickerContainer.backgroundColor = UIColor.white
let doneButton = UIButton()
doneButton.setTitle("Done", for: .normal)
doneButton.setTitleColor(UIColor.blue, for: .normal)
doneButton.addTarget(self, action: #selector(dismissPicker), for: UIControlEvents.touchUpInside)
doneButton.frame = CGRect(x: 250.0, y: 5.0, width: 70.0, height: 40.0)
datePickerContainer.addSubview(doneButton)
timePicker.frame = CGRect(x: 0.0, y: 40.0, width: self.view.frame.width, height: 200.0)
timePicker.datePickerMode = UIDatePickerMode.time
timePicker.backgroundColor = UIColor.white
timePicker.addTarget(self, action: #selector(CreateActivityViewController.startTimeDiveChanged), for: UIControlEvents.valueChanged)
datePickerContainer.addSubview(timePicker)
self.view.addSubview(datePickerContainer)
}
#objc func startTimeDiveChanged(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.timeStyle = .short
expectedTimeBtn.setTitle(formatter.string(from: sender.date), for: .normal)
}
#objc func dismissPicker() {
datePickerContainer.removeFromSuperview()
}

Related

How can I show done button on the decimal pad keyboard?

I'm trying to learn Swift and I've done on the view screens. But as you can understand more easily by checking the screenshot, when I enter a value into a text field, there isn't any done button showing up so I can not hide the keyboard from the screen. And that makes it impossible to press the submit button which is located bottom of the screen view.
Firstly, create a new Swift File. Add this to the file :
import Foundation
import UIKit
extension UIViewController{
func toolBar() -> UIToolbar{
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.barTintColor = UIColor.init(red: 0/255, green: 25/255, blue: 61/255, alpha: 1) //Write what you want for color
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
var buttonTitle = "Done" //Or "Tamam"
var cancelButtonTitle = "Cancel" //Or "İptal" for Turkish
let doneButton = UIBarButtonItem(title: buttonTitle, style: .done, target: self, action: #selector(onClickDoneButton))
let cancelButton = UIBarButtonItem(title: cancelButtonTitle, style: .plain, target: self, action: #selector(onClickCancelButton))
doneButton.tintColor = .white
cancelButton.tintColor = .white
toolBar.setItems([cancelButton, space, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
toolBar.sizeToFit()
return toolBar
}
#objc func onClickDoneButton(){
view.endEditing(true)
}
#objc func onClickCancelButton(){
view.endEditing(true)
}
}
And add this toolbar to your textfield :
yourTextField.inputAccessoryView = toolBar()
Hope it helps...
You can add a toolbar as an input accessory :
let toolBar = UIToolbar()
toolBar.sizeToFit()
let button = UIBarButtonItem(title: "Done", style: .plain, target: self,
action: #selector(dismiss))
toolBar.setItems([button], animated: true)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar
Also you need to add dismiss method:
#objc func dismiss() {
view.endEditing(true)
}
Without switching back to UIKit Used the following library
Link: https://github.com/siteline/SwiftUI-Introspect
import SwiftUI
import Introspect
struct ContentView : View {
#State var text = ""
var body: some View {
TextField("placeHolder", text: $text)
.keyboardType(.default)
.introspectTextField { (textField) in
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textField.frame.size.width, height: 44))
let flexButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textField.doneButtonTapped(button:)))
doneButton.tintColor = .systemPink
toolBar.items = [flexButton, doneButton]
toolBar.setItems([flexButton, doneButton], animated: true)
textField.inputAccessoryView = toolBar
}
}
extension UITextField {
#objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
self.resignFirstResponder()
}
}

Opening UIDatePicker under UITextView

I am writing an app, where when clicking on a UITexView an UIDatePicker opens. I want the UIDatePicker to pop up underneath the UITextView and not to come up as the keyboard from the bottom.
I am just starting with IOS app development and I hope someone can help me.
datePicker = UIDatePicker
and
inputTextfield = UITextField
myCode:
//Function to create the datepicker
func createDatePicker(){
//create instance of the datepicker
datePicker = UIDatePicker()
//sets format, so only day month and year can be selected
//datePicker?.datePickerMode = .date
datePicker?.backgroundColor = .white
datePicker?.addTarget(self, action: #selector(ViewController.dateChanged(datePicker:)), for: .valueChanged)
//to limit the datepicker, you can not pick a date older than yesterday
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
datePicker?.minimumDate = yesterday
datePicker?.minuteInterval = 30
let loc = Locale(identifier: "de")
datePicker?.locale = loc
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gesturRecognizer:)))
view.addGestureRecognizer(tapGesture)
inputTextfield.inputView = datePicker
//create a toolbar
let toolbar = UIToolbar()
toolbar.sizeToFit()
//add done button to the toolbar
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
toolbar.setItems([doneButton], animated: true)
inputTextfield.inputAccessoryView = toolbar
}
//function to select a date
#objc func dateChanged(datePicker: UIDatePicker){
//selected date by the user
let dateFormate = DateFormatter()
//Jonas das ist vllt für dich relevant, man kann es so verändern wie man will
dateFormate.dateFormat = "MM/dd/yyyy"
inputTextfield.text = dateFormate.string(from: datePicker.date)
}
//function to close the datepicker, when tapping on the inputText again -handler method
#objc func viewTapped(gesturRecognizer: UITapGestureRecognizer){
view.endEditing(true)
}
//function to close the datepicker when clicking on the done button
#objc func doneClicked(){
self.view.endEditing(true)
}
No need to use any third party library. This can be achieved very easily. What I understand is that you want the picker to be displayed below the textfield and not as the input view instead of keyboard. Follow the following code to achieve what you want.
Here, name of my ViewController is TextFieldWithDatePickerVC. Don't get confused with name. With following code you would be able to do this very easily without using any third part library. I am attaching a output video also along with the code.
class TextFieldWithDatePickerVC: UIViewController {
lazy var inputTextfield: UITextField = {
let txtField = UITextField()
txtField.backgroundColor = .white
txtField.borderStyle = .roundedRect
txtField.translatesAutoresizingMaskIntoConstraints = false
txtField.placeholder = "Click me to open date picker"
return txtField
}()
lazy var datePicker: UIDatePicker = {
let picker = UIDatePicker()
picker.backgroundColor = .white
picker.addTarget(self, action: #selector(TextFieldWithDatePickerVC.dateChanged(_:)), for: .valueChanged)
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
picker.minimumDate = yesterday
picker.minuteInterval = 30
let loc = Locale(identifier: "de")
picker.locale = loc
picker.translatesAutoresizingMaskIntoConstraints = false
return picker
}()
lazy var doneToolBar: UIToolbar = {
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
toolbar.setItems([doneButton], animated: true)
toolbar.translatesAutoresizingMaskIntoConstraints = false
return toolbar
}()
lazy var pickerContainer: UIView = {
let view = UIView()
view.backgroundColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
setupAutoLayout()
pickerContainer.isHidden = true
inputTextfield.delegate = self
hideDatePicker()
}
func showDatePickerView() {
DispatchQueue.main.async {
self.pickerContainer.isHidden = false
}
}
func hideDatePicker() {
DispatchQueue.main.async {
self.pickerContainer.isHidden = true
}
}
func setupAutoLayout() {
self.view.addSubview(inputTextfield)
self.view.addSubview(pickerContainer)
self.view.bringSubview(toFront: pickerContainer)
pickerContainer.addSubview(doneToolBar)
pickerContainer.addSubview(datePicker)
NSLayoutConstraint.activate([
inputTextfield.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30),
inputTextfield.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30),
inputTextfield.topAnchor.constraint(equalTo: view.topAnchor, constant: 60),
pickerContainer.topAnchor.constraint(equalTo: inputTextfield.bottomAnchor, constant: 5),
pickerContainer.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30),
pickerContainer.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30),
pickerContainer.heightAnchor.constraint(equalToConstant: datePicker.intrinsicContentSize.height + doneToolBar.intrinsicContentSize.height),
doneToolBar.topAnchor.constraint(equalTo: pickerContainer.topAnchor, constant: 0),
doneToolBar.leftAnchor.constraint(equalTo: pickerContainer.leftAnchor, constant: 0),
doneToolBar.rightAnchor.constraint(equalTo: pickerContainer.rightAnchor, constant: 0),
datePicker.bottomAnchor.constraint(equalTo: pickerContainer.bottomAnchor, constant: 0),
datePicker.leftAnchor.constraint(equalTo: pickerContainer.leftAnchor, constant: 0),
datePicker.rightAnchor.constraint(equalTo: pickerContainer.rightAnchor, constant: 0)
])
}
#objc func dateChanged(_ sender: UIDatePicker) {
print(sender.date)
inputTextfield.text = sender.date.description
}
#objc func doneClicked() {
hideDatePicker()
}
}
extension TextFieldWithDatePickerVC: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.resignFirstResponder()
showDatePickerView()
}
}
Here is a third party library which I guess will meet your expectation :
https://github.com/angelopino/APJTextPickerView
This subclasses the UITextField and very useful. Refer the example for more details.
See this: This would be helpfull for you.
https://blog.apoorvmote.com/change-textfield-input-to-datepicker/
let dateFormatter = DateFormatter()
let locale = NSLocale.current
var datePicker : UIDatePicker!
let toolBar = UIToolbar()
func doDatePicker() {
// DatePicker
self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: UIScreen.main.bounds.height - 200.0, width: UIScreen.main.bounds.width, height: 200))
self.datePicker?.backgroundColor = UIColor.white
self.datePicker?.datePickerMode = UIDatePickerMode.dateAndTime
datePicker.center = view.center
view.addSubview(self.datePicker)
// ToolBar
toolBar.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 240.0, width: UIScreen.main.bounds.width, height: 44.0)
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()
// Adding Button ToolBar
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneClick))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelClick))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: true)
self.view.addSubview(toolBar)
self.toolBar.isHidden = false
}
#objc func doneClick() {
let dateFormatter1 = DateFormatter()
dateFormatter1.dateStyle = .medium
dateFormatter1.timeStyle = .none
//self.datePicker.resignFirstResponder()
datePicker.isHidden = true
self.toolBar.isHidden = true
}
#objc func cancelClick() {
datePicker.isHidden = true
self.toolBar.isHidden = true
}

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

How to create Custom UI Date PickerViews in the same UIView in swift

Im trying to have two different date pickerViews on the same viewController and let them represent different data. I have tried a different ways to do this, but both date picker views showing same Data, but can't put it all together.I'm new to swift programming. Any help would be awesome!
#IBOutlet weak var EventStart: UITextField!
var datepicker = UIDatePicker()
var datepicker2 = UIDatePicker()
#IBOutlet weak var EventEnd: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
createDatePicker()
Event.delegate = self
eventName.delegate = self
// Do any additional setup after loading the view.
}
func createDatePicker(){
datepicker.datePickerMode = .dateAndTime
datepicker2.datePickerMode = .dateAndTime
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
toolbar.setItems([doneButton], animated: false)
EventEnd.inputAccessoryView = toolbar
EventEnd.inputView = datepicker2
EventStart.inputAccessoryView = toolbar
EventStart.inputView = datepicker
}
func donePressed(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
EventStart.text = dateFormatter.string(from: datepicker.date)
EventEnd.text = dateFormatter.string(from: datepicker2.date)
print(EventStart)
print(EventEnd)
self.view.endEditing(true)
}
#IBOutlet weak var EventStart: UITextField!
var datepicker = UIDatePicker()
var datepicker2 = UIDatePicker()
#IBOutlet weak var EventEnd: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.addDatePicker(datepicker, textfield:EventStart , selector: #selector(ViewController.donePressed))
self.addDatePicker(datepicker2 , textfield:EventEnd ,selector: #selector(ViewController.donePressed2))
// Do any additional setup after loading the view.
}
func addDatePicker(_ datepicker : UIDatePicker, textfield: UITextField, selector: Selector) {
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action:selector)
toolbar.setItems([doneButton], animated: false)
textfield.inputAccessoryView = toolbar
textfield.inputView = datepicker
}
func donePressed(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
EventStart.text = dateFormatter.string(from: datepicker.date)
print(EventStart)
self.view.endEditing(true)
}
func donePressed2(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
EventEnd.text = dateFormatter.string(from: datepicker2.date)
print(EventEnd)
self.view.endEditing(true)
}
The simple thing is to create two separate method for two of em. Also do not initialized them on view load.
This is my code for doing it.
var objDatePickerFrom: UIDatePicker!
var objDatePickerTo: UIDatePicker!
Then on respective button tap, I init them as below (you also do this in textview's delegate method if you do not use buttons.)
#IBAction func btnFromDateTapped(_ sender: UIButton) {
self.initDatePikerFrom(frame: self.view.frame)
}
#IBAction func btnToDateTapped(_ sender: UIButton) {
self.initDatePikerTo(frame: self.view.frame)
}
Below are the methods for init the date pickers.
func initDatePikerFrom(frame: CGRect) {
self.objDatePickerFrom = UIDatePicker()
objDatePickerFrom.backgroundColor = UIColor.white
objDatePickerFrom.datePickerMode = .date
if DeviceType.IS_IPHONE_4_OR_LESS
{
objDatePickerFrom?.frame.size = CGSize(width: frame.size.width, height: 150)
}
self.txtFromDate.inputView = objDatePickerFrom
objDatePickerFrom.maximumDate = Date()
if self.txtFromDate.text! != "" {
objDatePickerFrom.date = CommonFunctions.getDate(date: self.txtFromDate.text!)
}
self.view.bringSubview(toFront: objDatePickerFrom)
let numberToolbar = UIToolbar(frame: CGRect.init(x: 0.0, y: 0.0, width: frame.size.width, height: 40.0))
numberToolbar.barStyle = UIBarStyle.default
numberToolbar.barTintColor = NavigationBGColor
numberToolbar.layer.borderColor = UIColor(red: 79.0/255.0, green: 157.0/255.0, blue: 191.0/255.0, alpha: 1.0).cgColor
numberToolbar.layer.borderWidth = 0.0
let lblSelect = UILabel(frame: CGRect.init(x: 0, y: 0, width: 150, height: 30))
lblSelect.text = "Select Date"
lblSelect.textColor = WhiteFontColor
lblSelect.textAlignment = .center
let btnBarCancel = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(MyAccountViewController.btnCancelFromDateClick(_:)) )
btnBarCancel.tintColor = WhiteFontColor
let btnBarDone = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(MyAccountViewController.btnDoneFromDateClick(_:)) )
btnBarDone.tintColor = WhiteFontColor
numberToolbar.items = [
btnBarCancel,
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
UIBarButtonItem.init(customView: lblSelect),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
btnBarDone]
numberToolbar.sizeToFit()
self.txtFromDate.inputAccessoryView = numberToolbar
self.txtFromDate.isUserInteractionEnabled = true
self.txtFromDate.delegate = self
self.txtFromDate.becomeFirstResponder()
}
func initDatePikerTo(frame: CGRect) {
self.objDatePickerTo = UIDatePicker()
self.objDatePickerTo.backgroundColor = UIColor.white
self.objDatePickerTo.datePickerMode = .date
if DeviceType.IS_IPHONE_4_OR_LESS
{
self.objDatePickerTo?.frame.size = CGSize(width: frame.size.width, height: 150)
}
self.txtToDate.inputView = self.objDatePickerTo
self.objDatePickerTo.maximumDate = Date()
if self.txtToDate.text! != "" {
self.objDatePickerTo.date = CommonFunctions.getDate(date: self.txtToDate.text!)
}
self.view.bringSubview(toFront: self.objDatePickerTo)
let numberToolbar = UIToolbar(frame: CGRect.init(x: 0.0, y: 0.0, width: frame.size.width, height: 40.0))
numberToolbar.barStyle = UIBarStyle.default
numberToolbar.barTintColor = NavigationBGColor
numberToolbar.layer.borderColor = UIColor(red: 79.0/255.0, green: 157.0/255.0, blue: 191.0/255.0, alpha: 1.0).cgColor
numberToolbar.layer.borderWidth = 0.0
let lblSelect = UILabel(frame: CGRect.init(x: 0, y: 0, width: 150, height: 30))
lblSelect.text = "Select Date"
lblSelect.textColor = WhiteFontColor
lblSelect.textAlignment = .center
let btnBarCancel = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(MyAccountViewController.btnCancelToDateClick(_:)) )
btnBarCancel.tintColor = WhiteFontColor
let btnBarDone = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(MyAccountViewController.btnDoneToDateClick(_:)) )
btnBarDone.tintColor = WhiteFontColor
numberToolbar.items = [
btnBarCancel,
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
UIBarButtonItem.init(customView: lblSelect),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
btnBarDone]
numberToolbar.sizeToFit()
self.txtToDate.inputAccessoryView = numberToolbar
self.txtToDate.isUserInteractionEnabled = true
self.txtToDate.delegate = self
self.txtToDate.becomeFirstResponder()
}
The other related methods similar to your donePressed() are as below.
func btnDoneFromDateClick(_ sendre: AnyObject)
{
let date = CommonFunctions.getStrDate(date: self.objDatePickerFrom.date)
self.txtFromDate.text = "\(date.day) \(date.month) \(date.year)"
self.txtFromDate.resignFirstResponder()
self.txtFromDate.isUserInteractionEnabled = false
}
func btnDoneToDateClick(_ sendre: AnyObject)
{
let date = CommonFunctions.getStrDate(date: self.objDatePickerTo.date)
self.txtToDate.text = "\(date.day) \(date.month) \(date.year)"
self.txtToDate.resignFirstResponder()
self.txtToDate.isUserInteractionEnabled = false
}
May this will help you.
Happy Coding :)

Swift IOS - Using UIPickerView AND Keyboard

In my app when user clicks on UITextField he should be able to pick up a value from UIPickerView OR enter his own value using keyboard.
What's the best way of doing it in terms of user experience and ease of implementation?
UIPickerView with toolbar is already implemented.
I'd appreciate both advice on best way of doing it and example code of switching keyboard <-> pickerview.
I've tried adding a button "Show keyboard" on pickerview's toolbar and adding the following code:
func showKeyboard() {
selectedTextField.inputView = nil
}
But clicking this button doesn't do anything. Also I'm not sure it's a good way in terms of UX.
Here's the solution:
var useKeyboard:Bool = true
func showKeyboard() {
if useKeyboard {
useKeyboard = false
selectedTextField.inputView = nil
selectedTextField.reloadInputViews()
selectedTextField.keyboardAppearance = UIKeyboardAppearance.Default
selectedTextField.keyboardType = UIKeyboardType.Default
} else {
useKeyboard = true
selectedTextField.inputView = nil
selectedTextField.reloadInputViews()
createPicker(selectedTextField)
selectedTextField.resignFirstResponder()
selectedTextField.becomeFirstResponder()
}
}
// That's my custom picker - adjust whatever you need
func createPicker(sender: UITextField){
selectedTextField = sender
// Create picker view
var newPickerView: UIPickerView
newPickerView = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
newPickerView.backgroundColor = .whiteColor()
// Only for UIPickerView
newPickerView.showsSelectionIndicator = true
newPickerView.delegate = self
newPickerView.dataSource = self
// Create toolbar
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()
// Create buttons
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelPicker")
var customButton = UIBarButtonItem(title: "Keyboard", style: UIBarButtonItemStyle.Plain, target: self, action: "showKeyboard")
// Assign buttons to toolbar
toolBar.setItems([cancelButton, spaceButton, customButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
// Add pickerview and toolbar to textfield
sender.inputView = newPickerView
sender.inputAccessoryView = toolBar
}
func donePicker() {
useKeyboard = true
selectedTextField.resignFirstResponder()
}
func cancelPicker() {
useKeyboard = true
selectedTextField.resignFirstResponder()
}

Resources