iOS Revisited: UIDatePicker

Hot

Post Top Ad

Showing posts with label UIDatePicker. Show all posts
Showing posts with label UIDatePicker. Show all posts

29 Aug 2017

Add UIDatePicker as Input View to UITextField Swift - iOS

8/29/2017 10:16:00 am 0
In this article we are going to add UIDatePicker as Keyboard to UITextField and also adding UIToolBar above UIDatePicker.

This Article Covers All Related questions  :

UITextField UIDatePicker inputview Example.
uidatepicker inputview uitextfield.
uidatepicker and inputview swift.
uidatepicker inputview example.
UITextField input with a UIDatePicker.
UIDatePicker pop up after UITextField is Tapped.
Display date picker on UITextField touch.


Read Getting Started with UIDatePicker Tutorial.

Final Output from this article will looks like as follow:

Add UIDatePicker as Input View to UITextField Swift

In this whole project we are not going to use Storyboards. We are adding all views programmatically using autoLayouts.

Add UITextField :

First we are going to add UITextField to the view in ViewController. So declare textField variable before viewDidLoad() as:
var textField = UITextField()

Then add textField to the view by adding following method :
func addTextField() {
    view.addSubview(textField)
    textField.translatesAutoresizingMaskIntoConstraints = false
    textField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0).isActive = true
    textField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40.0).isActive = true
    textField.topAnchor.constraint(equalTo: view.topAnchor, constant: 40.0).isActive = true
    textField.placeholder = "Select date"
    textField.borderStyle = .roundedRect
}

Call addTextField() method inside viewDidLoad() method.

Build and run, we see an textField with an placeholder as 'Select date'.

Add Textfiled Programitically
On tapping textField keyboard will appear from bottom, that's ok. But our target is to get UIDatePicker instead of Keyboard.

No worries, it's easy to achieve.

Add UIDatePicker As Keyboard :

First we need to create UIDatePicker, so declare datePicker object after textField declaration as follow:
var textField = UITextField()
var datePicker = UIDatePicker()

Now initialize and add target to datePicker as follow:
func createDatePicker() {
    datePicker.datePickerMode = .date
    datePicker.addTarget(self, action: #selector(self.datePickerValueChanged(datePicker:)), for: .valueChanged)
}

We set datePickerMode to date only, because we need date only. Then add response method datePickerValueChanged(datePicker:) as follow:
@objc func datePickerValueChanged(datePicker: UIDatePicker) {
    
}

Above method will call every time user scrolls UIDatePicker.

Call createDatePicker() method before addTextField() line inside viewDidLoad() method.

So we created datePicker, but not linked to textField. For that we need to set textField inputView as datePicker. So add the following line at the end of addTextField() method :
textField.inputView = datePicker

Build and run, we see textField, then tap on texfield. Great UIDatePicker is showing up as follow:

TextField With DatePicker

So every time user changes date we should update in textField text. So we need to add following code inside datePickerValueChanged() method :
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none

textField.text = dateFormatter.string(from: datePicker.date)

What we have done here is that, we created dateFormatter with dateStyle as medium and timeStyle as none, because we don't need time.

And finally we are getting Date from datePicker.date, so we are converting Date to string and displaying in textField.

Run the project, we see same as before then select your date it will update in textFiled also.

TextField With DatePicker

Add UIToolBar To UIDatePicker :

Now for adding toolBar over UIDatePicker, we need to first create UIToolBar. so declare toolBar object after datePicker declaration as follow:
var textField = UITextField()
var datePicker = UIDatePicker()
var toolBar = UIToolbar()

Next initialize UIToolBar and add following UIBarButtonItem to toolBar as follow:
func createToolBar() {
    toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 40))
    
    let todayButton = UIBarButtonItem(title: "Today", style: .plain, target: self, action: #selector(todayButtonPressed(sender:)))
    
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed(sender:)))
    
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width/3, height: 40))
    label.text = "Choose your Date"
    let labelButton = UIBarButtonItem(customView:label)
    
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
    
    toolBar.setItems([todayButton,flexibleSpace,labelButton,flexibleSpace,doneButton], animated: true)
}

What we have done here is that, created four UIBarButtonItem.

todayButton:

Shortcut for selecting today's date. On tapping this button we are calling following method :
@objc func todayButtonPressed(sender: UIBarButtonItem) {
    let dateFormatter = DateFormatter() // 1
    dateFormatter.dateStyle = .medium
    dateFormatter.timeStyle = .none
    
    textField.text = dateFormatter.string(from: Date()) // 2
    
    textField.resignFirstResponder()
}

1. Here again added required dateFormatter, but here we want today's date so simply use Date() property to get current date.

2. Then we are converting to string by using dateFormatter.

3. Dismissing the keyboard(here date picker) using resignFirstResponder() method.

doneButton :

After selecting our date we should dismiss datePicker, this button is for that. On tapping this button we are calling following method :
@objc func doneButtonPressed(sender: UIBarButtonItem) {
    textField.resignFirstResponder()
}

labelButton :

LabelButton is like a placeholder text, we can't add UILabel to UIToolbar so we created custom UIBarButtonItem for adding label.

We can customize that label what ever we like.

flexibleSpace :

FlexibleSpace is for giving equal spaces between items in UIToolBar. FlexibleSpace is also of type UIBarButtonItem.flexibleSpace.

We added all four buttons to toolBar as required order.

Call createToolBar() method before addTextField() line inside viewDidLoad() method.

Good, created toolbar but How to add over datePicker?

Its easy, we are going to set textField inputAccessoryView as toolBar, add following code at the end of addTextField() method:
textField.inputAccessoryView = toolBar

Now Build and run, tap on textfield.

Great we can see UIDatePicker with toolBar on it.

UITextField UIDatePicker inputview Example.

Download sample project with examples :

Read More

28 Aug 2017

Selecting Date and Time with UIDatePicker - iOS, Swift

8/28/2017 09:40:00 am 0

UIDatePicker :

Apple made a ready-made user interface for picking data and time. We can use in our apps using UIDatePicker class.

The date picker is in fact a prepopulated picker view. Example of the date picker control is in the Calendar app, Clock app on the devices.

This Article Covers All Related questions  :

iOS DatePicker tutorial (UIDatePicker) using Swift.
UIDatePicker example in Swift.
Getting Started with the UIDatePicker for iOS Using Swift.
Creating or Making UIDatePicker programmatically.



UIDatePicker image

Example Project :

First create a new project  open Xcode -> File -> New -> Project -> Single View App, then tap next button. Type product name as 'DatePicker' then tap next and select the folder to save project.

Let’s get started by first declaring a property of type UIDatePicker. Add following line above viewDidLoad() method:
var datePicker = UIDatePicker()

Add datePicker object to the view of our view controller. Add following method:
func adddatePicker() {
    view.addSubview(datePicker)
    datePicker.translatesAutoresizingMaskIntoConstraints = false
    datePicker.heightAnchor.constraint(equalToConstant: 250).isActive = true
    datePicker.leadingAnchor.constraint(equalTo:view.leadingAnchor).isActive = true
    datePicker.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    datePicker.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
}

Call adddatePicker() method inside viewDidLoad() method.

Now let’s Build & run the app and see how it looks

Adding UIDatePicker as Input View to UITextField Swift

We can see that the date picker, by default, has picked today’s date. UIDatePicker supports different modes. We can change mode by using datePickerMode property, of type UIDatePickerMode. Default mode is dateAndTime.

Based on our need,we can set the mode of date picker to any of the values listed in the UIDatePickerMode enumeration.
enum UIDatePickerMode : Int {
    
    case time // Displays hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. 6 | 53 | PM)

    case date // Displays month, day, and year depending on the locale setting (e.g. November | 15 | 2007)

    case dateAndTime // Displays date, hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. Wed Nov 15 | 6 | 53 | PM)

    case countDownTimer // Displays hour and minute (e.g. 1 | 53)
}

Just like UIButton, UIDatePicker sends action messages to its targets whenever the user scrolls date picker. Add following method, like so:
func datePickerChanged(datePicker: UIDatePicker){
    print("date = \(datePicker.date)")
}

To response to these messages, the receiver must add itself as the target of the date picker, add addTarget:action:forControlEvents: method in the end of adddatePicker() method, like so:
datePicker.addTarget(self, action: #selector(datePickerChanged(datePicker:)), for: .valueChanged)

Build and Run, every time the user scroll picker view, we will get message of the selected date from date picker.

The good thing about UIDatePicker is that, we can set maximum date and minimum date limits. So set the minimumDate and maximumDate properties to date picker as by adding following code at the end of adddatePicker() method:
let currentDate = Date()
let oneDay = 24 * 60 * 60
let minDate = currentDate.addingTimeInterval(TimeInterval(-10 * oneDay)) // before 10 days from now
let maxDate = currentDate.addingTimeInterval(TimeInterval(20 * oneDay)) // upto 20 Days from now

datePicker.minimumDate = minDate
datePicker.maximumDate = maxDate

We can then limit the user’s selection on the date to a specific range. In this example code, we limited the user’s input of dates to the range of 10 days to 20 days from now.

Run and try to select the date out of our range, it scrolls back to our limits.


Date picker as a countdown timer, you must set your date picker mode to UIDatePickerModeCountDownTimer and use the countDownDuration property of the date picker to specify the default countdown duration.

Suppose if we want to set default count Down duration to 5 min, then write the following code at the end of adddatePicker() method:
datePicker.datePickerMode = .countDownTimer
let fiveMin = TimeInterval(5 * 60)
datePicker.countDownDuration = fiveMin

Build and run, we can see result as follow :


Download sample project with examples :

Read More

Post Top Ad