Sign In

Popup a UIPickerView from the bottom of a UIScrollView in response to a UITextField selection

  1. Create a UIPickerView and position it off-screen initially:
let pickerView = UIPickerView()
pickerView.frame = CGRect(x: 0, y: view.frame.height, width: view.frame.width, height: 216)
view.addSubview(pickerView)
  1. Set up the UITextField to show the picker instead of the keyboard:
textField.inputView = pickerView
  1. Create a toolbar with a “Done” button to dismiss the picker:
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(dismissPicker))
toolbar.setItems([doneButton], animated: false)
textField.inputAccessoryView = toolbar
  1. Implement the dismissPicker method:
@objc func dismissPicker() {
    view.endEditing(true)
}
  1. Animate the picker to slide up from the bottom when the text field is selected:
textField.addTarget(self, action: #selector(textFieldDidBeginEditing), for: .editingDidBegin)

@objc func textFieldDidBeginEditing() {
    UIView.animate(withDuration: 0.3) {
        self.pickerView.frame.origin.y = self.view.frame.height - self.pickerView.frame.height
    }
}
  1. Make sure to adjust the UIScrollView’s content inset when the picker is shown:
scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: pickerView.frame.height, right: 0)
  1. Reset the scroll view’s content inset when the picker is dismissed:
@objc func dismissPicker() {
    view.endEditing(true)
    UIView.animate(withDuration: 0.3) {
        self.pickerView.frame.origin.y = self.view.frame.height
        self.scrollView.contentInset = .zero
    }
}

This approach will:

  • Create a UIPickerView positioned off-screen initially
  • Show the picker instead of the keyboard for the text field
  • Animate the picker sliding up from the bottom when the text field is selected
  • Adjust the scroll view’s content inset to accommodate the picker
  • Provide a “Done” button to dismiss the picker and reset the scroll view

Remember to implement the UIPickerViewDelegate and UIPickerViewDataSource protocols to populate the picker with data and handle selections.

Citations:
[1] https://stackoverflow.com/questions/594181/making-a-uitableview-scroll-when-text-field-is-selected/24085537
[2] https://github.com/flutter/flutter/issues/102484
[3] https://github.com/flutter/flutter/issues/91980
[4] https://support.google.com/docs/thread/258137048/selecting-or-deselecting-text-will-automatically-scroll-up-to-the-top-of-the-text-block?hl=en
[5] https://stackoverflow.com/questions/76926923/issue-with-scrolling-text-selection-in-flutter-textformfield

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *