I'm looking for a way to present a UIPickerView
when the user taps on a UIBarButtonItem
. Imagine a filter for the table view results.
I know I could use a UITextField
inputView, but this would not be the case -- all I have is a UIBarButtonItem
and a UITableView
.
I've seen into using a UIActionSheet, but it does not look natural, specially when it's animating to show.
Would animating the UIView
on and off the screen manually the only option?
The app is iOS 6+ and iPhone only, so I don't need to keep compatibility with any other versions/idioms.
A better option is still to use the
UITextField
. You don't have to actually show it on screen. Just put it in a 0x0UIView
so that it is not visible, set it'sinputView
to yourUIPickerView
and callbecomeFirstResponder
on it to show the picker andresignFirstResponder
to hide it.It is convenient to have a
UIView
subclass that implements all of that along withUIPickerViewDelegate
andUIPickerViewDataSource
methods.Attach a UIPickerView as the inputView of a 0-sized UITextField that you have added to your view.
The cleanest way at least for me, and for Swift4 + Autolayout solution, without a
UITextField
is adding aUIView
as a container of theUIPickerView
and aUIToolbar
for the top views/buttons.Then toggle the inset/offset of that container view with animation if you want, to hide and unhide the picker.
PROPERTIES
I use
SnapKit
to layout my views programmatically. You can use thetimePicker
's bounds.size as reference for your layout.IMPLEMENTATION
In viewDidLoad()
Embedding top views
And the result looks like this:
I went with borisgolovnev's suggestion of an invisible
UITextField
and came up with the following Swift 2.3 implementation:PickerViewPresenter can then conveniently be used as such:
Hope someone finds this useful =)
It might not be your only option but animating the UIPickerView should be relatively easy for you to do. Add the picker view so it's displayed off the bottom of the screen. When it's time to animate it in:
And when it's time to hide it: