Change text in a PickerView - translation

I used this code in Objective C to change language in a PickerView:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.dicke = [[NSArray alloc]
initWithObjects:#"0.0",#"0.5",#"1.0",#"1.5",#"2.0",#"2.5",#"3.0",#"4.0",#"5.0",#"6.0",#"8.0",#"10.0",#"12.0",#"15.0",#"20.0", nil];
NSString *userLocale = [[NSLocale currentLocale] localeIdentifier];
NSLog(#"%#", userLocale);
if ([userLocale isEqualToString:#"de_DE"]) {
self.Material = [[NSArray alloc]
initWithObjects:#"Stahl",#"Aluminium",#"Edelstahl",#"Kupfer", nil];
}
else
self.Material = [[NSArray alloc]
initWithObjects:#"Steel",#"Aluminum",#"Stainless",#"Copper", nil];
}
How can i do this in Swift, or is there another way to translate text in a PickerView. Sorry for this stupid question but I´m really a beginner with Swift.

Ok,
i fixed it with:
var material = [NSLocalizedString ("Steel", comment: ""),NSLocalizedString ("Aluminum", comment: ""),NSLocalizedString ("Stainless", comment: ""),NSLocalizedString ("Copper", comment: "")]
and use localizable.strings. That works fine!

In Swift 3.0
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
pickerLabel.textColor = (row == pickerView.selectedRow(inComponent: component)) ? UIColor.white : UIColor.white
pickerLabel.text = arrAgeLimite[row]
pickerLabel.font.withSize(90)
pickerLabel.textAlignment = NSTextAlignment.center
return pickerLabel
}

Related

UIPickerView Behaving Erratically

So I feel stupid asking about this, but I simply cannot figure out what is going wrong. Basically, when I click a textField that has a UIPickerView as its inputView it will show up very quickly and then disappear. However, the toolBar (its accessoryView still remains on screen). I haven't seen anyone else online who has experienced this, so that's why I had to ask it on SO.
At first I thought it had something do with when I was setting the pickerView's .isHidden property. But I omitted those calls to no effect.
Thus, I will be including all of the code related to my pickerViews since I really don't know where the issue is. I'm sure it's something minor I'm missing, but any help would be appreciated.
class myAssessmentsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet weak var contentSelectionTextField: UITextField!
#IBOutlet weak var contentOrderingTextField: UITextField!
var contentSelectionPickerView: UIPickerView = UIPickerView()
var contentOrderingPickerView: UIPickerView = UIPickerView()
var contentSelectionOptions: [String] = ["All", "Physics HL", "Chemistry HL", "Spanish Ab SL"]
var contentOrderingOptions: [String] = ["Date", "Subject", "Grade", "Title"]
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
contentSelectionPickerView.tag = 1 //for the delegate methods
contentSelectionPickerView.isHidden = true //commenting this out did nothing
contentSelectionPickerView.delegate = self
contentSelectionPickerView.dataSource = self
contentSelectionTextField.inputView = contentSelectionPickerView //set pickerView as responder
contentSelectionTextField.delegate = self
contentOrderingPickerView.tag = 2 //for the delegate methods
contentOrderingPickerView.isHidden = true //commenting this out also did nothing
contentOrderingPickerView.delegate = self
contentOrderingPickerView.dataSource = self
initializePickerViewToolBar(clearButtonFunc: "clearPressedContentSelectionPickerView", doneButtonFunc: "donePressedContentSelectionPickerView", textField: contentSelectionTextField)
initializePickerViewToolBar(clearButtonFunc: "clearPressedContentOrderingPickerView", doneButtonFunc: "donePressedContentOrderingPickerView", textField: contentOrderingTextField)
contentOrderingTextField.inputView = contentOrderingPickerView //set pickerView as responder
contentOrderingTextField.delegate = self
// Do any additional setup after loading the view.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1 //same for both pickers
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 1 { //contentSelectionPickerView
return contentSelectionOptions.count
} else if pickerView.tag == 2 { //contentOrderingPickerView
return contentOrderingOptions.count
} else {
return 1
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
self.view.endEditing(true)
if pickerView.tag == 1 { //contentSelectionPickerView
return contentSelectionOptions[row]
} else if pickerView.tag == 2 { //contentOrderingPickerView
return contentOrderingOptions[row]
} else {
return "1"
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 1 {
contentSelectionTextField.text = contentSelectionOptions[row]
} else if pickerView.tag == 2 {
contentOrderingTextField.text = contentOrderingOptions[row]
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == contentSelectionTextField {
contentSelectionPickerView.isHidden = false //also was not source of problem
} else if textField == contentOrderingTextField {
contentOrderingPickerView.isHidden = false //same here
}
}
func donePressedContentSelectionPickerView(){
contentSelectionTextField.resignFirstResponder()
}
func donePressedContentOrderingPickerView(){
contentOrderingTextField.resignFirstResponder()
}
func clearPressedContentSelectionPickerView(){
contentSelectionTextField.resignFirstResponder()
contentSelectionTextField.text = ""
}
func clearPressedContentOrderingPickerView(){
contentOrderingTextField.resignFirstResponder()
contentOrderingTextField.text = ""
}
func initializePickerViewToolBar(clearButtonFunc: String, doneButtonFunc: String, textField: UITextField){
let toolBar = UIToolbar(frame: CGRect(x: 0, y: textField.frame.size.height/6, width: textField.frame.size.width, height: 40.0))
toolBar.layer.position = CGPoint(x: textField.frame.size.width/2, y: textField.frame.size.height-20.0)
toolBar.barStyle = .default
toolBar.tintColor = UIColor.black
let clearButton = UIBarButtonItem(title: "Clear", style: .plain, target: self, action: Selector(clearButtonFunc))
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: Selector(doneButtonFunc))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolBar.setItems([clearButton,flexSpace,doneButton], animated: true)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar
}
}
Here is also a photo of what I am talking about visually. As you can see at the bottom of the screen the accessoryView is still visible but the content isn't. I would think that the accessoryView would be a subview of the UIPickerView and that they would disappear together but that is apparently not the case.
Again, apologies for all of the code (and the large image), I know it is a lot to read through, but any insight would be greatly appreciated!
So it turns out that one of the answers from SO that I was following told me to include self.view.endEditing(true) in my pickerViewTitleForRow delegate method. This meant whenever the titles were being set, the first responder was being dismissed, causing this issue. Removing it caused the problem to disappear. Thanks to #MikeTaverne for pointing it out.

Swift - Adding a pickerView to a textfield in UIViewController

I am struggling a bit with optionals and setting up views and subviews by using an #IBOutlet. I am currently trying to create a controller to add a user to the database. One of my fields is related to the user's gender, so I want it to be linked to a UIPickerView. I am not using Storyboard.
I removed all the other fields from my code to make it a lot shorter and readable, but it will also have other UIPickerView fields (like birthday).
Can someone help me with my code so that my textfield will display a UIPickerView when selected?
class AddUserController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
var picker: UIPickerView = UIPickerView()
var genderData = ["Male", "Female"]
// Containers
let inputsContainerView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.whiteColor()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.masksToBounds = true
return view
}()
// Subviews
#IBOutlet weak var genderTextField: UITextField! = {
var gender = UITextField()
gender.placeholder = "Gender"
gender.translatesAutoresizingMaskIntoConstraints = false
gender.leftViewMode = UITextFieldViewMode.Always
gender.autocorrectionType = .No
let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 120, height: 30))
lbl.text = "GENDER"
lbl.font = UIFont.boldSystemFontOfSize(12)
gender.leftView = lbl
return gender
}()
override func viewDidLoad() {
super.viewDidLoad()
picker = UIPickerView()
picker.dataSource = self
picker.delegate = self
picker.hidden = true
genderTextField?.delegate = self
genderTextField?.inputView = picker
genderTextField?.text = genderData[0]
view.backgroundColor = UIColor(white: 0.95, alpha: 1)
view.addSubview(inputsContainerView)
setupInputsContainerView()
}
// Picker functions
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return genderData.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return genderData[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
genderTextField.text = genderData[row]
self.view.endEditing(true)
picker.hidden = true
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
picker.hidden = false
return true
}
// Setup all the views
func setupInputsContainerView() {
inputsContainerView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
inputsContainerView.topAnchor.constraintEqualToAnchor(view.bottomAnchor, constant: 12).active = true
inputsContainerView.widthAnchor.constraintEqualToAnchor(view.widthAnchor, constant: -24).active = true
inputsContainerView.heightAnchor.constraintEqualToConstant(40).active = true
inputsContainerView.addSubview(genderTextField)
genderTextField.leftAnchor.constraintEqualToAnchor(inputsContainerView.leftAnchor, constant: 12).active = true
genderTextField.topAnchor.constraintEqualToAnchor(inputsContainerView.topAnchor).active = true
genderTextField.widthAnchor.constraintEqualToAnchor(inputsContainerView.widthAnchor).active = true
genderTextField.heightAnchor.constraintEqualToAnchor(inputsContainerView.heightAnchor).active = true
}
}
genderTextField is getting created every time you call that.
genderTextField?.delegate = self
genderTextField?.inputView = picker
genderTextField?.text = genderData[0]
All these are different objects
inputsContainerView.addSubview(genderTextField)
What you added here is also different. So the textField you adedd to the view and the delegate/datasource you added are all different. One quick solution is to move
genderTextField?.delegate = self
genderTextField?.inputView = picker
genderTextField?.text = genderData[0]
these code after this line inputsContainerView.addSubview(genderTextField)

Different UIPickerView Delegate/DataSource in UIAlertController

Please tell me how make two different UIPickerView with different delegate/datasource? I have TableView with two cells, and i need open two different UIAlertController with UIPickerView. My code:
private weak var filterController: UIAlertController! {
let controllerConfig = UIAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n", preferredStyle: .Alert)
controllerConfig.modalInPopover = true
//Create UIPickerView
let pickerFrame = CGRectMake(0, 20, 270, 180)
let picker = UIPickerView(frame: pickerFrame)
//Picker Color
picker.backgroundColor = controllerConfig.view.backgroundColor
//Picker Delegate/DataSource
picker.delegate = self
picker.dataSource = self
//Add Picker
controllerConfig.view.addSubview(picker)
//Create header frame
let headerFrame = CGRectMake(0, 5, 270, 45)
let headerView = UIView(frame: headerFrame)
headerView.backgroundColor = controllerConfig.view.backgroundColor
//Create 'Close' button
var closeButton: UIButton! {
let buttonFrame = CGRectMake(230, 5, 35, 35)
let buttonConfig = UIButton(frame: buttonFrame)
buttonConfig.setTitle("X", forState: .Normal)
//Set color on text
buttonConfig.setTitleColor(UIColor.grayColor(), forState: .Normal)
buttonConfig.setTitleColor(erablagoThemeColor, forState: .Highlighted)
buttonConfig.addTarget(self, action: #selector(didClickOnCloseButton), forControlEvents: .TouchUpInside)
return buttonConfig
}
let showAction = UIAlertAction(title: "Select", style: .Default) { (action) in
//TODO
}
//Add subview
headerView.addSubview(closeButton)
controllerConfig.addAction(showAction)
controllerConfig.view.addSubview(headerView)
return controllerConfig
}
///Close current view
func didClickOnCloseButton() {
dismissViewControllerAnimated(true, completion: nil)
}
And i have implementation UIPickerViewDelegate and UIPickerViewDataSource. I need change this implementation in my ViewContriller.
//MARK: - UIPickerViewDataSource
extension FilterController: UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 2
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch row {
case 0:
return "All"
case 1:
return "Cars and Bicycles"
default:
return nil
}
}
}
May be me need create class with UIAlertController and call him in my ViewController? I don't know. Thank you in advance:]
When you say you want the pickers to have different delegates it you are suggesting that different classes are responsible for handling the delegate methods. Thus the following will solve your problem:
picker.delegate = self
picker2.delegate = anotherClassInstance
But I don't think thats what you're asking. I think you are asking how to have two different pickers with different data both being handled by the same class, and thus share the same delegate class. The easiest way to do this is assign the tag property on each picker:
picker.delegate = self
picker.tag = 1
picker2.delegate = self
picker2.tag = 2
Then, differentiate between them as so:
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if picker.tag == 1 {
switch row {
case 0:
return "All"
case 1:
return "Cars and Bicycles"
default:
return nil
} else {
switch row {
case 0:
return "None"
case 1:
return "Other picker data"
default:
return nil
}
}
Ok, I made new class with UIPickerDelegate/DataSource and made new instance this class. My code looks like that:
Delegate class:
class SortFilterPicker: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 4
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch row {
case 0:
return "1-1"
case 1:
return "2-2"
case 2:
return "3-3"
case 3:
return "4-4"
default:
return nil
}
}
}
And main code:
private let categoryFilter = FilterPicker()
private weak var filterController: UIAlertController! {
var heightPopUp = "\n"
let controllerConfig = UIAlertController(title: "", message: heightPopUp.repeatOf(9), preferredStyle: .Alert)
controllerConfig.modalInPopover = true
let pickerFrame = CGRectMake(0, 20, 270, 180)
let picker = UIPickerView(frame: pickerFrame)
picker.delegate = categoryFilter
picker.dataSource = categoryFilter
picker.backgroundColor = controllerConfig.view.backgroundColor
controllerConfig.view.addSubview(picker)
let headerFrame = CGRectMake(0, 5, 270, 45)
let headerView = UIView(frame: headerFrame)
headerView.backgroundColor = controllerConfig.view.backgroundColor
var closeButton: UIButton! {
let buttonFrame = CGRectMake(230, 5, 35, 35)
let buttonConfig = UIButton(frame: buttonFrame)
buttonConfig.setTitle("X", forState: .Normal)
//Set color on text
buttonConfig.setTitleColor(UIColor.grayColor(), forState: .Normal)
buttonConfig.setTitleColor(erablagoThemeColor, forState: .Highlighted)
buttonConfig.addTarget(self, action: #selector(didClickOnCloseButton), forControlEvents: .TouchUpInside)
return buttonConfig
}
let showAction = UIAlertAction(title: "Ok", style: .Default) { (action) in
//TODO: Make show
}
headerView.addSubview(closeButton)
controllerConfig.addAction(showAction)
controllerConfig.view.addSubview(headerView)
return controllerConfig
}
It's works :]

Error occur while put a image stored as NSdata into the pickerView

I use core Data to store my image as NSdata, so the image will be stored from another TableViewController
Now, I would try to put a image stored as a NSData into the pickerView
var restaurants:Restaurant!
var imageArray = [NSData]()
var dataArray1 = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
imageArray = [restaurants.image!]
for(var i = 0; i < 100; i++) {
dataArray1.append((Int)(arc4random() % 10))
}
resultLabel.text = ""
pickerView.delegate = self
pickerView.dataSource = self
}
#IBAction func buttonClicked(sender: AnyObject) {
pickerView.selectRow(Int(arc4random())%94 + 3, inComponent: 0, animated: true)
}
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
let pickerImage = UIImageView()
if component == 0 {
_ = imageArray[(Int)(dataArray1[row])]
}
return pickerImage
}
it looks like the view below, but the image inside should be my NSData files
http://www.appcoda.com.tw/wp-content/uploads/2015/08/emoji-slotmachine.gif
When I run it, it always shut down.
I think the problem is that Array doesn't get the value from the Core Data?
Really need help, please.
You are not properly converting your NSData representing a UIImage back to a UIImage. Because of this, the cast that you are trying to do fails every time.
Check out this question:
To summarize for you:
To get a UIImage, you need this line somewhere:
image = [UIImage imageWithData:data];

Show UIPickerView like a keyboard, without UITextField

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.
Attach a UIPickerView as the inputView of a 0-sized UITextField that you have added to your view.
let picker = UIPickerView()
picker.dataSource = self
picker.delegate = self
let dummy = UITextField(frame: .zero)
view.addSubview(dummy)
dummy.inputView = picker
dummy.becomeFirstResponder()
A better option is still to use the UITextField. You don't have to actually show it on screen. Just put it in a 0x0 UIView so that it is not visible, set it's inputView to your UIPickerView and call becomeFirstResponder on it to show the picker and resignFirstResponder to hide it.
It is convenient to have a UIView subclass that implements all of that along with UIPickerViewDelegate and UIPickerViewDataSource methods.
The cleanest way at least for me, and for Swift4 + Autolayout solution, without a UITextField is adding a UIView as a container of the UIPickerView and a UIToolbar 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
private lazy var view_PickerContainer: UIView = {
let view = UIView()
view.backgroundColor = .white
view.addSubview(self.timePicker)
view.addSubview(self.toolbar_Picker)
return view
}()
private lazy var timePicker: UIDatePicker = {
let picker = UIDatePicker()
picker.minimumDate = Date()
picker.datePickerMode = .time
picker.setDate(Date(), animated: true)
return picker
}()
private let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
return formatter
}()
private lazy var toolbar_Picker: UIToolbar = {
let toolbar = UIToolbar()
toolbar.barStyle = .blackTranslucent
toolbar.barTintColor = .blueDarkText
toolbar.tintColor = .white
self.embedButtons(toolbar)
return toolbar
}()
I use SnapKit to layout my views programmatically. You can use the timePicker's bounds.size as reference for your layout.
IMPLEMENTATION
In viewDidLoad()
// Setup timepicker and its container.
self.view.addSubview(self.view_PickerContainer)
self.view_PickerContainer.snp.makeConstraints { (make) in
make.height.equalTo(self.timePicker.bounds.size.height + 50.0)
make.leading.trailing.equalToSuperview()
self.constraint_PickerContainerBottom = make.bottom.equalToSuperview().inset(-500.0).constraint
}
self.timePicker.snp.makeConstraints { (make) in
make.height.equalTo(self.timePicker.bounds.size.height)
make.width.equalToSuperview()
make.bottom.equalToSuperview()
}
// Add toolbar for buttons.
self.toolbar_Picker.snp.makeConstraints { (make) in
make.height.equalTo(40.0)
make.top.leading.trailing.equalToSuperview()
}
Embedding top views
private func embedButtons(_ toolbar: UIToolbar) {
func setupLabelBarButtonItem() -> UIBarButtonItem {
let label = UILabel()
label.text = "Set Alarm Time"
label.textColor = .white
return UIBarButtonItem(customView: label)
}
let todayButton = UIBarButtonItem(title: "Today", style: .plain, target: self, action: #selector(self.todayPressed(_:)))
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.donePressed(_:)))
let flexButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolbar.setItems([todayButton, flexButton, setupLabelBarButtonItem(), flexButton, doneButton], animated: true)
}
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:
import UIKit
class PickerViewPresenter: UITextField {
// MARK: - Initialization
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(frame: CGRect.zero)
inputView = pickerView
inputAccessoryView = pickerInputAccessoryView
}
// MARK: - Public
var pickerDelegate: UIPickerViewDelegate? {
didSet {
pickerView.delegate = pickerDelegate
}
}
var pickerDataSource: UIPickerViewDataSource? {
didSet {
pickerView.dataSource = pickerDataSource
}
}
var selectButtonAction: (() -> Void)?
var currentlySelectedRow: Int {
return pickerView.selectedRowInComponent(0)
}
func selectRowAtIndex(index: Int) {
pickerView.selectRow(index, inComponent: 0, animated: false)
}
func showPicker() {
self.becomeFirstResponder()
}
func hidePicker() {
self.resignFirstResponder()
}
// MARK: - Views
private let pickerView = UIPickerView(frame: CGRect.zero)
private lazy var pickerInputAccessoryView: UIView = {
let frame = CGRect(x: 0.0, y: 0.0, width: 0.0, height: 48.0)
let pickerInputAccessoryView = UIView(frame: frame)
// Customize the view here
return pickerInputAccessoryView
}()
func selectButtonPressed(sender: UIButton) {
selectButtonAction?()
}
}
PickerViewPresenter can then conveniently be used as such:
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(pickerViewPresenter)
}
private let dataModel = [10, 20, 30, 40, 50]
private lazy var pickerViewPresenter: PickerViewPresenter = {
let pickerViewPresenter = PickerViewPresenter()
pickerViewPresenter.pickerDelegate = self
pickerViewPresenter.pickerDataSource = self
pickerViewPresenter.selectButtonAction = { [weak self] () -> Void in
guard let strongSelf = self else {
return
}
let result = strongSelf.dataModel[pickerViewPresenter.currentlySelectedRow]
pickerViewPresenter.hidePicker()
// ...
}
return pickerViewPresenter
}()
private func presentPickerView {
let index = 0 // [0..dataModel.count-1]
pickerViewPresenter.selectRowAtIndex(index)
pickerViewPresenter.showPicker()
}
// MARK: - UIPickerViewDataSource
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataModel.count
}
// MARK: - UIPickerViewDelegate
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return "\(dataModel[row]) drunken sailors"
}
}
Hope someone finds this useful =)
Based on borisgolovnev's suggestion and CodeMonkey's answer, I have implemented the idea with an invisible UITextField in the following way in Swift 5.
import UIKit
class PickerViewPresenter: UITextField, UIPickerViewDataSource, UIPickerViewDelegate {
private lazy var doneToolbar: UIToolbar = {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped))
let items = [flexSpace, doneButton]
toolbar.items = items
toolbar.sizeToFit()
return toolbar
}()
private lazy var pickerView: UIPickerView = {
let pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
return pickerView
}()
var items: [Item] = []
var didSelectItem: ((Item) -> Void)?
private var selectedItem: Item?
init() {
super.init(frame: .zero)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
inputView = pickerView
inputAccessoryView = doneToolbar
}
#objc private func doneButtonTapped() {
if let selectedItem = selectedItem {
didSelectItem?(selectedItem)
}
resignFirstResponder()
}
func showPicker() {
becomeFirstResponder()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return items.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return items[row].name
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedItem = items[row]
}
}
Usage in your ViewController:
private var selectedItem: Item?
private lazy var pickerViewPresenter: PickerViewPresenter = {
let pickerViewPresenter = PickerViewPresenter()
pickerViewPresenter.didSelectItem = { [weak self] item in
self?.selectedItem = item
}
return pickerViewPresenter
}()
view.addSubview(pickerViewPresenter)
// e.g. on a button tap
#objc private func buttonTapped() {
pickerViewPresenter.showPicker()
}
Example:
I have attached it to a UITapGestureRecognizer.
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:
[UIView animateWithDuration:0.3 animations:^{
self.datePicker.frame = CGRectMake(0, self.view.bounds.size.height - datePicker.bounds.size.height, datePicker.bounds.size.width, datePicker.bounds.size.height);
}];
And when it's time to hide it:
[UIView animateWithDuration:0.3 animations:^{
self.datePicker.frame = CGRectMake(0, self.view.bounds.size.height, datePicker.bounds.size.width, datePicker.bounds.size.height);
}];

Resources