Initiating UIDatePicker with same size as keyboard on iPhone X (and higher)












0















I'm trying to construct a UIDatePicker which has the same height as the user's keyboard observed with the keyboardDiDShow notification.



The keyboardHeight is observed with an NotificationCenter Observer after the keyboard is displayed. The UIDatePicker is initialized in the custom TableViewCell awakeFromNib() function. The problem is that the keyboardHeight is only observed after the keyboard did show which happens AFTER the call of awakeFromNib(). Is there a way to update the UIDatePicker height after it has been initialized?



TableViewController



Observer:



`NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardDidShowNotification , object: nil)`


Keyboard Height:



@objc func keyboardWillShow(notification: Notification) -> CGFloat {
NSLog("Keyboard appeared")
if let keyboardSize = (notification.userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let heigth = keyboardSize.height
keyboardHeight = heigth
print(keyboardHeight)
return heigth
}
return 0


TableViewCell



UIDatePicker Initialization:



let picker = UIDatePicker()
let tableView = ItemsTableViewController()

override func awakeFromNib() {
// Initialization
super.awakeFromNib()
// UIDatePicker features
picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
picker.datePickerMode = .date
picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

// Size
let screenWidth = UIScreen.main.bounds.width
let size = CGSize(width: screenWidth, height: tableView.keyboardHeight)
let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
picker.frame = frame

// Add toolbar to picker
let toolbar = UIToolbar()
toolbar.sizeToFit()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

toolbar.setItems([flexibleSpace, doneButton], animated: true)
dateTextField.inputAccessoryView = toolbar


The outcome is that the UIDatePicker is created with a height of 0 because the keyboard did not show up yet when the picker was created.










share|improve this question



























    0















    I'm trying to construct a UIDatePicker which has the same height as the user's keyboard observed with the keyboardDiDShow notification.



    The keyboardHeight is observed with an NotificationCenter Observer after the keyboard is displayed. The UIDatePicker is initialized in the custom TableViewCell awakeFromNib() function. The problem is that the keyboardHeight is only observed after the keyboard did show which happens AFTER the call of awakeFromNib(). Is there a way to update the UIDatePicker height after it has been initialized?



    TableViewController



    Observer:



    `NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardDidShowNotification , object: nil)`


    Keyboard Height:



    @objc func keyboardWillShow(notification: Notification) -> CGFloat {
    NSLog("Keyboard appeared")
    if let keyboardSize = (notification.userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
    let heigth = keyboardSize.height
    keyboardHeight = heigth
    print(keyboardHeight)
    return heigth
    }
    return 0


    TableViewCell



    UIDatePicker Initialization:



    let picker = UIDatePicker()
    let tableView = ItemsTableViewController()

    override func awakeFromNib() {
    // Initialization
    super.awakeFromNib()
    // UIDatePicker features
    picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
    picker.datePickerMode = .date
    picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

    // Size
    let screenWidth = UIScreen.main.bounds.width
    let size = CGSize(width: screenWidth, height: tableView.keyboardHeight)
    let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
    picker.frame = frame

    // Add toolbar to picker
    let toolbar = UIToolbar()
    toolbar.sizeToFit()
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

    toolbar.setItems([flexibleSpace, doneButton], animated: true)
    dateTextField.inputAccessoryView = toolbar


    The outcome is that the UIDatePicker is created with a height of 0 because the keyboard did not show up yet when the picker was created.










    share|improve this question

























      0












      0








      0








      I'm trying to construct a UIDatePicker which has the same height as the user's keyboard observed with the keyboardDiDShow notification.



      The keyboardHeight is observed with an NotificationCenter Observer after the keyboard is displayed. The UIDatePicker is initialized in the custom TableViewCell awakeFromNib() function. The problem is that the keyboardHeight is only observed after the keyboard did show which happens AFTER the call of awakeFromNib(). Is there a way to update the UIDatePicker height after it has been initialized?



      TableViewController



      Observer:



      `NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardDidShowNotification , object: nil)`


      Keyboard Height:



      @objc func keyboardWillShow(notification: Notification) -> CGFloat {
      NSLog("Keyboard appeared")
      if let keyboardSize = (notification.userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
      let heigth = keyboardSize.height
      keyboardHeight = heigth
      print(keyboardHeight)
      return heigth
      }
      return 0


      TableViewCell



      UIDatePicker Initialization:



      let picker = UIDatePicker()
      let tableView = ItemsTableViewController()

      override func awakeFromNib() {
      // Initialization
      super.awakeFromNib()
      // UIDatePicker features
      picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
      picker.datePickerMode = .date
      picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

      // Size
      let screenWidth = UIScreen.main.bounds.width
      let size = CGSize(width: screenWidth, height: tableView.keyboardHeight)
      let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
      picker.frame = frame

      // Add toolbar to picker
      let toolbar = UIToolbar()
      toolbar.sizeToFit()
      let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
      let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

      toolbar.setItems([flexibleSpace, doneButton], animated: true)
      dateTextField.inputAccessoryView = toolbar


      The outcome is that the UIDatePicker is created with a height of 0 because the keyboard did not show up yet when the picker was created.










      share|improve this question














      I'm trying to construct a UIDatePicker which has the same height as the user's keyboard observed with the keyboardDiDShow notification.



      The keyboardHeight is observed with an NotificationCenter Observer after the keyboard is displayed. The UIDatePicker is initialized in the custom TableViewCell awakeFromNib() function. The problem is that the keyboardHeight is only observed after the keyboard did show which happens AFTER the call of awakeFromNib(). Is there a way to update the UIDatePicker height after it has been initialized?



      TableViewController



      Observer:



      `NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardDidShowNotification , object: nil)`


      Keyboard Height:



      @objc func keyboardWillShow(notification: Notification) -> CGFloat {
      NSLog("Keyboard appeared")
      if let keyboardSize = (notification.userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
      let heigth = keyboardSize.height
      keyboardHeight = heigth
      print(keyboardHeight)
      return heigth
      }
      return 0


      TableViewCell



      UIDatePicker Initialization:



      let picker = UIDatePicker()
      let tableView = ItemsTableViewController()

      override func awakeFromNib() {
      // Initialization
      super.awakeFromNib()
      // UIDatePicker features
      picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
      picker.datePickerMode = .date
      picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

      // Size
      let screenWidth = UIScreen.main.bounds.width
      let size = CGSize(width: screenWidth, height: tableView.keyboardHeight)
      let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
      picker.frame = frame

      // Add toolbar to picker
      let toolbar = UIToolbar()
      toolbar.sizeToFit()
      let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
      let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

      toolbar.setItems([flexibleSpace, doneButton], animated: true)
      dateTextField.inputAccessoryView = toolbar


      The outcome is that the UIDatePicker is created with a height of 0 because the keyboard did not show up yet when the picker was created.







      ios swift xcode






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 1 at 16:44









      NiklasNiklas

      66




      66
























          1 Answer
          1






          active

          oldest

          votes


















          0














          To directly answer your question, there's a way to update the height of the picker. You just need to be able to reference the picker from your keyboardWillShow implementation:



          cell.picker.frame.height = keyboardSize.height





          EDIT:



          Just realized that you're probably composing your cell in the Interface builder (xib or storyboard), which means that you're already using Autolayout. Just setting the picker's height won't do the trick here. You'd have to add a NSLayoutConstraint for picker's height in interface builder, and set its constant property to match the keyboard's height once the keyboard appears. Something like:



          cell.datePickerHeightConstraint.constant = keyboardSize.height



          I still think you should consider using the solution mentioned below.





          However, it seems to me that you're not going with the easiest approach. The easiest approach would be setting the picker as the dateTextField's inputView. This way the picker would be displayed instead of the keyboard. Change your awakeFromNib implementation to:



          override func awakeFromNib() {

          // Initialization
          super.awakeFromNib()
          // UIDatePicker features
          picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
          picker.datePickerMode = .date
          picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

          // Add toolbar to picker
          let toolbar = UIToolbar()
          toolbar.sizeToFit()
          let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
          let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

          toolbar.setItems([flexibleSpace, doneButton], animated: true)
          dateTextField.inputAccessoryView = toolbar
          dateTextField.inputView = picker


          Also, if you're interested in writing your UI code in a modern way, you should use Autolayout instead of directly setting frame of your UIViews: https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/index.html





          EDIT 2:



          Embedding a UIDatePicker in a UIInputView subclass allows for matching the keyboard height:



          class DatePickerInputView: UIInputView {
          let datePicker = UIDatePicker()

          var height: CGFloat = 320 {
          didSet {
          heightConstraint?.constant = height
          }
          }
          private var heightConstraint: NSLayoutConstraint?

          override var inputViewStyle: UIInputView.Style {
          get { return .default }
          }

          override var allowsSelfSizing: Bool {
          get { return true }
          set {}
          }

          init() {
          super.init(frame: .zero, inputViewStyle: .default)
          addSubview(datePicker)

          translatesAutoresizingMaskIntoConstraints = false
          datePicker.translatesAutoresizingMaskIntoConstraints = false
          let heightConstraint = datePicker.heightAnchor.constraint(equalToConstant: height)

          NSLayoutConstraint.activate([
          datePicker.topAnchor.constraint(equalTo: topAnchor),
          datePicker.bottomAnchor.constraint(equalTo: bottomAnchor),
          datePicker.leadingAnchor.constraint(equalTo: leadingAnchor),
          datePicker.trailingAnchor.constraint(equalTo: trailingAnchor),
          heightConstraint
          ])
          self.heightConstraint = heightConstraint
          }

          required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
          }
          }


          Then change the height in your keyboardWillShow:



          datePicker.height = keyboardSize.height


          Here's a repo with this approach: https://github.com/AleksanderMaj/DatePickerInputView






          share|improve this answer


























          • Thanks for your reply. Actually I’m using your approach with setting the inputView. My problem is that the DatePicker doesn’t have the same height as the keyboard, so when switching between textfields with normal keyboard and datepicker inputs, the frames are jumping around because keyboard and datepicker do not have the same height

            – Niklas
            Jan 1 at 21:05











          • Check my update answer.

            – Aleksander Maj
            Jan 1 at 22:02











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997195%2finitiating-uidatepicker-with-same-size-as-keyboard-on-iphone-x-and-higher%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          To directly answer your question, there's a way to update the height of the picker. You just need to be able to reference the picker from your keyboardWillShow implementation:



          cell.picker.frame.height = keyboardSize.height





          EDIT:



          Just realized that you're probably composing your cell in the Interface builder (xib or storyboard), which means that you're already using Autolayout. Just setting the picker's height won't do the trick here. You'd have to add a NSLayoutConstraint for picker's height in interface builder, and set its constant property to match the keyboard's height once the keyboard appears. Something like:



          cell.datePickerHeightConstraint.constant = keyboardSize.height



          I still think you should consider using the solution mentioned below.





          However, it seems to me that you're not going with the easiest approach. The easiest approach would be setting the picker as the dateTextField's inputView. This way the picker would be displayed instead of the keyboard. Change your awakeFromNib implementation to:



          override func awakeFromNib() {

          // Initialization
          super.awakeFromNib()
          // UIDatePicker features
          picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
          picker.datePickerMode = .date
          picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

          // Add toolbar to picker
          let toolbar = UIToolbar()
          toolbar.sizeToFit()
          let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
          let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

          toolbar.setItems([flexibleSpace, doneButton], animated: true)
          dateTextField.inputAccessoryView = toolbar
          dateTextField.inputView = picker


          Also, if you're interested in writing your UI code in a modern way, you should use Autolayout instead of directly setting frame of your UIViews: https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/index.html





          EDIT 2:



          Embedding a UIDatePicker in a UIInputView subclass allows for matching the keyboard height:



          class DatePickerInputView: UIInputView {
          let datePicker = UIDatePicker()

          var height: CGFloat = 320 {
          didSet {
          heightConstraint?.constant = height
          }
          }
          private var heightConstraint: NSLayoutConstraint?

          override var inputViewStyle: UIInputView.Style {
          get { return .default }
          }

          override var allowsSelfSizing: Bool {
          get { return true }
          set {}
          }

          init() {
          super.init(frame: .zero, inputViewStyle: .default)
          addSubview(datePicker)

          translatesAutoresizingMaskIntoConstraints = false
          datePicker.translatesAutoresizingMaskIntoConstraints = false
          let heightConstraint = datePicker.heightAnchor.constraint(equalToConstant: height)

          NSLayoutConstraint.activate([
          datePicker.topAnchor.constraint(equalTo: topAnchor),
          datePicker.bottomAnchor.constraint(equalTo: bottomAnchor),
          datePicker.leadingAnchor.constraint(equalTo: leadingAnchor),
          datePicker.trailingAnchor.constraint(equalTo: trailingAnchor),
          heightConstraint
          ])
          self.heightConstraint = heightConstraint
          }

          required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
          }
          }


          Then change the height in your keyboardWillShow:



          datePicker.height = keyboardSize.height


          Here's a repo with this approach: https://github.com/AleksanderMaj/DatePickerInputView






          share|improve this answer


























          • Thanks for your reply. Actually I’m using your approach with setting the inputView. My problem is that the DatePicker doesn’t have the same height as the keyboard, so when switching between textfields with normal keyboard and datepicker inputs, the frames are jumping around because keyboard and datepicker do not have the same height

            – Niklas
            Jan 1 at 21:05











          • Check my update answer.

            – Aleksander Maj
            Jan 1 at 22:02
















          0














          To directly answer your question, there's a way to update the height of the picker. You just need to be able to reference the picker from your keyboardWillShow implementation:



          cell.picker.frame.height = keyboardSize.height





          EDIT:



          Just realized that you're probably composing your cell in the Interface builder (xib or storyboard), which means that you're already using Autolayout. Just setting the picker's height won't do the trick here. You'd have to add a NSLayoutConstraint for picker's height in interface builder, and set its constant property to match the keyboard's height once the keyboard appears. Something like:



          cell.datePickerHeightConstraint.constant = keyboardSize.height



          I still think you should consider using the solution mentioned below.





          However, it seems to me that you're not going with the easiest approach. The easiest approach would be setting the picker as the dateTextField's inputView. This way the picker would be displayed instead of the keyboard. Change your awakeFromNib implementation to:



          override func awakeFromNib() {

          // Initialization
          super.awakeFromNib()
          // UIDatePicker features
          picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
          picker.datePickerMode = .date
          picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

          // Add toolbar to picker
          let toolbar = UIToolbar()
          toolbar.sizeToFit()
          let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
          let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

          toolbar.setItems([flexibleSpace, doneButton], animated: true)
          dateTextField.inputAccessoryView = toolbar
          dateTextField.inputView = picker


          Also, if you're interested in writing your UI code in a modern way, you should use Autolayout instead of directly setting frame of your UIViews: https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/index.html





          EDIT 2:



          Embedding a UIDatePicker in a UIInputView subclass allows for matching the keyboard height:



          class DatePickerInputView: UIInputView {
          let datePicker = UIDatePicker()

          var height: CGFloat = 320 {
          didSet {
          heightConstraint?.constant = height
          }
          }
          private var heightConstraint: NSLayoutConstraint?

          override var inputViewStyle: UIInputView.Style {
          get { return .default }
          }

          override var allowsSelfSizing: Bool {
          get { return true }
          set {}
          }

          init() {
          super.init(frame: .zero, inputViewStyle: .default)
          addSubview(datePicker)

          translatesAutoresizingMaskIntoConstraints = false
          datePicker.translatesAutoresizingMaskIntoConstraints = false
          let heightConstraint = datePicker.heightAnchor.constraint(equalToConstant: height)

          NSLayoutConstraint.activate([
          datePicker.topAnchor.constraint(equalTo: topAnchor),
          datePicker.bottomAnchor.constraint(equalTo: bottomAnchor),
          datePicker.leadingAnchor.constraint(equalTo: leadingAnchor),
          datePicker.trailingAnchor.constraint(equalTo: trailingAnchor),
          heightConstraint
          ])
          self.heightConstraint = heightConstraint
          }

          required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
          }
          }


          Then change the height in your keyboardWillShow:



          datePicker.height = keyboardSize.height


          Here's a repo with this approach: https://github.com/AleksanderMaj/DatePickerInputView






          share|improve this answer


























          • Thanks for your reply. Actually I’m using your approach with setting the inputView. My problem is that the DatePicker doesn’t have the same height as the keyboard, so when switching between textfields with normal keyboard and datepicker inputs, the frames are jumping around because keyboard and datepicker do not have the same height

            – Niklas
            Jan 1 at 21:05











          • Check my update answer.

            – Aleksander Maj
            Jan 1 at 22:02














          0












          0








          0







          To directly answer your question, there's a way to update the height of the picker. You just need to be able to reference the picker from your keyboardWillShow implementation:



          cell.picker.frame.height = keyboardSize.height





          EDIT:



          Just realized that you're probably composing your cell in the Interface builder (xib or storyboard), which means that you're already using Autolayout. Just setting the picker's height won't do the trick here. You'd have to add a NSLayoutConstraint for picker's height in interface builder, and set its constant property to match the keyboard's height once the keyboard appears. Something like:



          cell.datePickerHeightConstraint.constant = keyboardSize.height



          I still think you should consider using the solution mentioned below.





          However, it seems to me that you're not going with the easiest approach. The easiest approach would be setting the picker as the dateTextField's inputView. This way the picker would be displayed instead of the keyboard. Change your awakeFromNib implementation to:



          override func awakeFromNib() {

          // Initialization
          super.awakeFromNib()
          // UIDatePicker features
          picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
          picker.datePickerMode = .date
          picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

          // Add toolbar to picker
          let toolbar = UIToolbar()
          toolbar.sizeToFit()
          let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
          let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

          toolbar.setItems([flexibleSpace, doneButton], animated: true)
          dateTextField.inputAccessoryView = toolbar
          dateTextField.inputView = picker


          Also, if you're interested in writing your UI code in a modern way, you should use Autolayout instead of directly setting frame of your UIViews: https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/index.html





          EDIT 2:



          Embedding a UIDatePicker in a UIInputView subclass allows for matching the keyboard height:



          class DatePickerInputView: UIInputView {
          let datePicker = UIDatePicker()

          var height: CGFloat = 320 {
          didSet {
          heightConstraint?.constant = height
          }
          }
          private var heightConstraint: NSLayoutConstraint?

          override var inputViewStyle: UIInputView.Style {
          get { return .default }
          }

          override var allowsSelfSizing: Bool {
          get { return true }
          set {}
          }

          init() {
          super.init(frame: .zero, inputViewStyle: .default)
          addSubview(datePicker)

          translatesAutoresizingMaskIntoConstraints = false
          datePicker.translatesAutoresizingMaskIntoConstraints = false
          let heightConstraint = datePicker.heightAnchor.constraint(equalToConstant: height)

          NSLayoutConstraint.activate([
          datePicker.topAnchor.constraint(equalTo: topAnchor),
          datePicker.bottomAnchor.constraint(equalTo: bottomAnchor),
          datePicker.leadingAnchor.constraint(equalTo: leadingAnchor),
          datePicker.trailingAnchor.constraint(equalTo: trailingAnchor),
          heightConstraint
          ])
          self.heightConstraint = heightConstraint
          }

          required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
          }
          }


          Then change the height in your keyboardWillShow:



          datePicker.height = keyboardSize.height


          Here's a repo with this approach: https://github.com/AleksanderMaj/DatePickerInputView






          share|improve this answer















          To directly answer your question, there's a way to update the height of the picker. You just need to be able to reference the picker from your keyboardWillShow implementation:



          cell.picker.frame.height = keyboardSize.height





          EDIT:



          Just realized that you're probably composing your cell in the Interface builder (xib or storyboard), which means that you're already using Autolayout. Just setting the picker's height won't do the trick here. You'd have to add a NSLayoutConstraint for picker's height in interface builder, and set its constant property to match the keyboard's height once the keyboard appears. Something like:



          cell.datePickerHeightConstraint.constant = keyboardSize.height



          I still think you should consider using the solution mentioned below.





          However, it seems to me that you're not going with the easiest approach. The easiest approach would be setting the picker as the dateTextField's inputView. This way the picker would be displayed instead of the keyboard. Change your awakeFromNib implementation to:



          override func awakeFromNib() {

          // Initialization
          super.awakeFromNib()
          // UIDatePicker features
          picker.minimumDate = Calendar.current.date(byAdding: DateComponents(), to: Date())
          picker.datePickerMode = .date
          picker.addTarget(self, action: #selector(pickerValueToText(_:)), for: .valueChanged)

          // Add toolbar to picker
          let toolbar = UIToolbar()
          toolbar.sizeToFit()
          let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
          let doneButton = UIBarButtonItem(title: "Next", style: .done, target: self, action: #selector(doneClicked))

          toolbar.setItems([flexibleSpace, doneButton], animated: true)
          dateTextField.inputAccessoryView = toolbar
          dateTextField.inputView = picker


          Also, if you're interested in writing your UI code in a modern way, you should use Autolayout instead of directly setting frame of your UIViews: https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/index.html





          EDIT 2:



          Embedding a UIDatePicker in a UIInputView subclass allows for matching the keyboard height:



          class DatePickerInputView: UIInputView {
          let datePicker = UIDatePicker()

          var height: CGFloat = 320 {
          didSet {
          heightConstraint?.constant = height
          }
          }
          private var heightConstraint: NSLayoutConstraint?

          override var inputViewStyle: UIInputView.Style {
          get { return .default }
          }

          override var allowsSelfSizing: Bool {
          get { return true }
          set {}
          }

          init() {
          super.init(frame: .zero, inputViewStyle: .default)
          addSubview(datePicker)

          translatesAutoresizingMaskIntoConstraints = false
          datePicker.translatesAutoresizingMaskIntoConstraints = false
          let heightConstraint = datePicker.heightAnchor.constraint(equalToConstant: height)

          NSLayoutConstraint.activate([
          datePicker.topAnchor.constraint(equalTo: topAnchor),
          datePicker.bottomAnchor.constraint(equalTo: bottomAnchor),
          datePicker.leadingAnchor.constraint(equalTo: leadingAnchor),
          datePicker.trailingAnchor.constraint(equalTo: trailingAnchor),
          heightConstraint
          ])
          self.heightConstraint = heightConstraint
          }

          required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
          }
          }


          Then change the height in your keyboardWillShow:



          datePicker.height = keyboardSize.height


          Here's a repo with this approach: https://github.com/AleksanderMaj/DatePickerInputView







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 1 at 22:02

























          answered Jan 1 at 20:26









          Aleksander MajAleksander Maj

          153111




          153111













          • Thanks for your reply. Actually I’m using your approach with setting the inputView. My problem is that the DatePicker doesn’t have the same height as the keyboard, so when switching between textfields with normal keyboard and datepicker inputs, the frames are jumping around because keyboard and datepicker do not have the same height

            – Niklas
            Jan 1 at 21:05











          • Check my update answer.

            – Aleksander Maj
            Jan 1 at 22:02



















          • Thanks for your reply. Actually I’m using your approach with setting the inputView. My problem is that the DatePicker doesn’t have the same height as the keyboard, so when switching between textfields with normal keyboard and datepicker inputs, the frames are jumping around because keyboard and datepicker do not have the same height

            – Niklas
            Jan 1 at 21:05











          • Check my update answer.

            – Aleksander Maj
            Jan 1 at 22:02

















          Thanks for your reply. Actually I’m using your approach with setting the inputView. My problem is that the DatePicker doesn’t have the same height as the keyboard, so when switching between textfields with normal keyboard and datepicker inputs, the frames are jumping around because keyboard and datepicker do not have the same height

          – Niklas
          Jan 1 at 21:05





          Thanks for your reply. Actually I’m using your approach with setting the inputView. My problem is that the DatePicker doesn’t have the same height as the keyboard, so when switching between textfields with normal keyboard and datepicker inputs, the frames are jumping around because keyboard and datepicker do not have the same height

          – Niklas
          Jan 1 at 21:05













          Check my update answer.

          – Aleksander Maj
          Jan 1 at 22:02





          Check my update answer.

          – Aleksander Maj
          Jan 1 at 22:02




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997195%2finitiating-uidatepicker-with-same-size-as-keyboard-on-iphone-x-and-higher%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          'app-layout' is not a known element: how to share Component with different Modules

          android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

          WPF add header to Image with URL pettitions [duplicate]