Monday, July 13, 2015

How to have 2 different UIPickerView for 2 different UITextField in the same UIViewController

Initial attempt:
drag 2 UIPickerView and control drag them and apply constraints to fit them to the bottom

However~
this will make your storyboard hard to maintain and messy, especially if you have UI elements that needed to be changed in the future.

The better solution could be:
Create 2 UIPickerView programatically

var statesPickerView: UIPickerView!
var phoneNumberPickerView: UIPickerView!

and then your toolbar(for Done or maybe stepper for form input)

var keyboardToolbar: UIToolbar!
keyboardToolbar = UIToolbar()
        keyboardToolbar.sizeToFit()
        var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
        var doneButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("dismissPickerView"))

        var barButtonItemsArray = NSMutableArray()
        barButtonItemsArray.addObject(flexSpace)
        barButtonItemsArray.addObject(doneButton)
        keyboardToolbar.items = barButtonItemsArray as [AnyObject]
        keyboardToolbar.sizeToFit()

add the toolbars to the inputview(picker view)
        self.phoneCodeTextField.inputAccessoryView = keyboardToolbar
        self.statesTextField.inputAccessoryView = keyboardToolbar
        self.phoneNumberPickerView = UIPickerView()
        self.statesPickerView = UIPickerView()

don't forget the delegates
        self.phoneNumberPickerView.dataSource = self
        self.statesPickerView.dataSource = self
        self.phoneNumberPickerView.delegate = self
        self.statesPickerView.delegate = self

 assign the pickerview as the inputview for the UITextFields
        self.phoneCodeTextField.inputView = phoneNumberPickerView
        self.statesTextField.inputView = statesPickerView


Another thing to note, you don't have to set the position or CGRectMake for your pickerview, thanks to the inputView property(e.g. your keyboard is at the bottom anyways).
Awesome <3

No comments:

Post a Comment