Date+Picker.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // Date+Picker.swift
  3. // LMS
  4. //
  5. // Created by Suraj Kumar Mandal on 03/10/23.
  6. //
  7. import Foundation
  8. import UIKit
  9. extension UITextField {
  10. func datePicker<T>(target: T,
  11. doneAction: Selector,
  12. cancelAction: Selector,
  13. datePickerMode: UIDatePicker.Mode = .date) {
  14. let screenWidth = UIScreen.main.bounds.width
  15. func buttonItem(withSystemItemStyle style: UIBarButtonItem.SystemItem) -> UIBarButtonItem {
  16. let buttonTarget = style == .flexibleSpace ? nil : target
  17. let action: Selector? = {
  18. switch style {
  19. case .cancel:
  20. return cancelAction
  21. case .done:
  22. return doneAction
  23. default:
  24. return nil
  25. }
  26. }()
  27. let barButtonItem = UIBarButtonItem(barButtonSystemItem: style,
  28. target: buttonTarget,
  29. action: action)
  30. return barButtonItem
  31. }
  32. let datePicker = UIDatePicker(frame: CGRect(x: 0,
  33. y: 0,
  34. width: screenWidth,
  35. height: 216))
  36. datePicker.datePickerMode = datePickerMode
  37. if #available(iOS 13.4, *) {
  38. datePicker.preferredDatePickerStyle = .wheels
  39. } else {
  40. // Fallback on earlier versions
  41. }
  42. datePicker.minimumDate = Date()
  43. self.inputView = datePicker
  44. let toolBar = UIToolbar(frame: CGRect(x: 0,
  45. y: 0,
  46. width: screenWidth,
  47. height: 44))
  48. toolBar.setItems([buttonItem(withSystemItemStyle: .cancel),
  49. buttonItem(withSystemItemStyle: .flexibleSpace),
  50. buttonItem(withSystemItemStyle: .done)],
  51. animated: true)
  52. self.inputAccessoryView = toolBar
  53. }
  54. }