Ufuk Canlı
Ufuk's Blog

Ufuk's Blog

Open up a UIPickerView when a UITableViewCell selected in UIKit

Open up a UIPickerView when a UITableViewCell selected in UIKit

Ufuk Canlı's photo
Ufuk Canlı
·Mar 11, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Recently, I've been doing the tasks that are given to me at work. One of them includes the current subject. I wasn't sure how to do that when I first saw the design files. I thought there might be changes in the design because usually we use UIActionSheet in these kind of situations. I've talked with our designer about this but she said they've already used this type of structure everywhere in the design.

This job needed to be done no matter what. So, stepped up and make some research on the subject. After some time, I've finally found a solution and I'd like to share with you guys. Who knows, maybe this blog post would solve someone's problem. :)

As you know already, UIPickerView works great with UITextField. You need your UITableViewCell to act like UITextField for a smooth UIPickerView experience. And to do that, you just need to conform some properties in your cell class.

override var canBecomeFirstResponder: Bool {
    return true
}

override var canResignFirstResponder: Bool {
    return true
}

override var inputView: UIView? {
    return picker
}

override var inputAccessoryView: UIView? {
    return toolbar
}

These codes just above assume that you declared a picker and a toolbar instance in your cell class. Toolbar is optional of course. If you just need a picker don't include the toolbar but you should know that toolbars are kind of brother and sister with pickers. :)

And now you just need to add these lines in your didSelectRowAt method. You may want to check the current indexPath to prevent the picker from opening up when you select a specific cell or vice versa.

 if let cell = tableView.cellForRow(at: indexPath) as? YourCustomUITableViewCell {
     if !cell.isFirstResponder { _ = cell.becomeFirstResponder() }
 }

Good job! I hope you find this trick useful. I'd like to these kind of short blog posts since I'm too busy with work, school and life in general. Thanks for reading and do not hesitate to share the post or show your appreciation by adding a comment in the comment line below.

Photo by Sergey Zolkin on Unsplash