Initially I wanted to add a hidden UIPickerView onto the Main.storyboard alongside my existing UISearchBar and when a BarButtonItem is clicked, the UIPickerView should be displayed; but it appears I cannot have them both at once in a given space.
So instead, my best alternative was to create it programmatically. I've followed existing tutorials (http://sourcefreeze.com/ios-uipickerview-example-using-swift/) and similar questions (Programmatically Create and Show UIPickerView) and seems like I do (?) have a UIPickerView as the description of it is being printed and I get the following:
<UIPickerView: 0x7f86425b1fb0; frame = (100 100; 100 162); layer = <CALayer: 0x7f8642543a20>>
Here is part of my current code which may be of help:
AnimalTableViewController.swift
import UIKit
class AnimalTableViewController: UITableViewController, UINavigationControllerDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet var segmentedSortOption: UISegmentedControl!
var array : NSArray = Animal.animalStruct.jsonResult["animal"] as NSArray
var filteredArray = [[String:AnyObject]]()
var timer = NSTimer()
var counter:Int = 1
var typePickerView: UIPickerView = UIPickerView()
#IBOutlet var typeBarButton: UIBarButtonItem!
var resultSearchController = UISearchController()
var indexArray:String!
#IBAction func refresh(sender: AnyObject) {
self.tableView.reloadData()
println("refreshed")
}
override func viewDidLoad() {
super.viewDidLoad()
self.typePickerView.hidden = true
self.typePickerView.dataSource = self
self.typePickerView.delegate = self
self.typePickerView.frame = CGRectMake(100, 100, 100, 162)
self.typePickerView.backgroundColor = UIColor.blackColor()
self.typePickerView.layer.borderColor = UIColor.whiteColor().CGColor
self.typePickerView.layer.borderWidth = 1
timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return array.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return array[row]["type1"] as String
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
typeBarButton.title = array[row]["type1"] as? String
typePickerView.hidden = false
}
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 36.0
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 36.0
}
#IBAction func typePickerViewSelected(sender: AnyObject) {
typePickerView.hidden = false
println(typePickerView.description)
}
}
Please could you help me display the programmatically created UIPickerView when the BarButtonItem is pressed? If you have any more questions, please do ask.
Many thanks.
You never add the pickerView as a subview of the ViewController, which you can do in viewDidLoad() since you're hiding it. Then when you unhide it your view should be there.
EDIT: Added Code
override func viewDidLoad() {
super.viewDidLoad()
self.typePickerView.hidden = true
//other pickerView code like dataSource and delegate
self.view.addSubview(pickerView) //will add the subview to the view hierarchy
}
With the above code, now when you unhide it on button press the view will show up.
Related
I am trying to follow the following solution to having multiple UIPickerViews on the one UIViewController. They suggest that a tag for each of the UITextfield which I have done and able to implement the number of rows, title for row and number of components. However, I have reached a stumbling block when implementing the did select row. When I select the UITextField it highlights another UITextfield. Below is the code I have so far.
class DriverViewController: UIViewController {
var selectedTrack: String?
var firstDriver: String?
var secondDriver: String?
var thirdDriver: String?
let tracks = ["Melbourne", "Manama", "Shanghai", "Baku",
"Barcelona", "Monaco", "Montreal","Le Castellet","Spielberg",
"Silverstone","Hockenheim","Budapest","Francorchamps","Monza","Singapore","Sochi","Suzuka","Austin","Interlagos","Abu Dhabi"]
let drivers = ["Lewis Hamilton","Antonio Giovinazzi","Kimi Raikkonen","Charles Leclerc","Sebastian Vettel","Romain Grosjean","Kevin Magnussen","Lando Norris",
"Carlos Sainz","Valtteri Bottas","Sergio Perez","Lance Stroll","Pierre Gasly","Max Verstappen","Nico Hulkenberg","Daniel Ricciardo","Alexander Albon","Daniil Kvyat","Robert Kubica","George Russell"]
#IBOutlet weak var TrackTextField: UITextField!
#IBOutlet weak var firstTextField: UITextField!
#IBOutlet weak var secondTextField: UITextField!
#IBOutlet weak var thirdTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
createTrackPicker()
createDriverPicker()
createToolBar()
// Do any additional setup after loading the view.
}
func createTrackPicker() {
let trackPicker = UIPickerView()
trackPicker.tag = 0
trackPicker.delegate = self
TrackTextField.inputView = trackPicker
}
func createDriverPicker() {
let driverPicker = UIPickerView()
driverPicker.tag = 1
driverPicker.tag = 2
driverPicker.tag = 3
driverPicker.delegate = self
firstTextField.inputView = driverPicker
secondTextField.inputView = driverPicker
thirdTextField.inputView = driverPicker
}
func createToolBar() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
TrackTextField.inputAccessoryView = toolBar
firstTextField.inputAccessoryView = toolBar
secondTextField.inputAccessoryView = toolBar
thirdTextField.inputAccessoryView = toolBar
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension DriverViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 0 {
return tracks.count
} else {
return drivers.count
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 0 {
return "\(tracks[row])"
} else {
return "\(drivers[row])"
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 0 {
selectedTrack = tracks[row]
TrackTextField.text = selectedTrack
} else if pickerView.tag == 1 {
firstDriver = drivers[row]
firstTextField.text = firstDriver
} else if pickerView.tag == 2 {
secondDriver = drivers[row]
secondTextField.text = secondDriver
} else if pickerView.tag == 3 {
thirdDriver = drivers[row]
thirdTextField.text = thirdDriver
}
}
}
This is how it looks on the screen.
Look at your function:
func createDriverPicker() {
let driverPicker = UIPickerView()
driverPicker.tag = 1
driverPicker.tag = 2
driverPicker.tag = 3
driverPicker.delegate = self
firstTextField.inputView = driverPicker
secondTextField.inputView = driverPicker
thirdTextField.inputView = driverPicker
}
Think about what value the tag property has after this code is run keeping in mind that it can only have one value.
You either need to update the picker view's tag property each time a text field begins editing, or you should abandon the use of the tag and simply check which text field is currently the first responder. See UIPickerView for each text field with different arrays (Swift/Firebase) for an example of how this is done.
It seems that I cannot select the very first row in the UIPickerView when I first load it. I want the textfield to update immediately when I load the picker view. It only updates when I select something else, and then go back to the first row.
var platformData = ["XBOX", "PS4", "PC"]
var picker = UIPickerView()
#IBOutlet var platformSelected: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
platformSelected.inputView = picker
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneAction))
toolbar.items = [doneButton]
platformSelected.inputAccessoryView = toolbar
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return platformData.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
platformSelected.text = platformData[row]
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return platformData[row]
}
Improve your code.
platformSelected.delegate = self
......
// MARK: - UITextFieldDelegate
extension YourUIViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
// TODO: - Specify index what you need. After editing it changed and you should get selected index using its position in platformData Array
let index = 0
picker.selectRow(index, inComponent: 0, animated: true)
}
}
I want to realize one simple app, but I have some trouble. I add textField and PickerView. When I tab at textField, PickerView is appeared. But standard keyboard is appeared too (I dont want it). And when I again tab on textField, PickerView don't appear. How can I receive this problem? Thank's a lot!
This is my code:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet weak var pickerView1: UIPickerView!
#IBOutlet weak var textField1: UITextField!
var age = ["8", "18", "28", "38", "48"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return age.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == pickerView1 {
}
return age[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == pickerView1 {
self.textField1.text = self.age[row]
self.pickerView1.isHidden = true
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == self.textField1 {
self.pickerView1.isHidden = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
why you are not try the simple way, just add your pickerview as inputview of your textfield
textField1.inputView = pickerView1
This will not give you a direct way to dismiss the view since your UIPickerView has no return button, which is why I recommend to use the inputAccessoryView property to display a toolbar with a done button
let myToolbar = UIToolbar(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(320), height: CGFloat(44)))
//should code with variables to support view resizing
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.inputAccessoryViewDidFinish))
//using default text field delegate method here, here you could call
//myTextField.resignFirstResponder to dismiss the views
myToolbar.setItems([doneButton], animated: false)
lblcurrentText.inputAccessoryView = myToolbar
and call the function as
func inputAccessoryViewDidFinish() {
lblcurrentText.resignFirstResponder()
}
at the same time after selection on your pickerview hide the text field like
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == pickerView1 {
self.textField1.text = self.age[row]
self.inputAccessoryViewDidFinish()
}
}
Tutorial
for example you can get the step by step tutorial in here
recently I need a solution to show a present-like pickerView for choosing data for some property, like profile.
what I did is
1, create a empty project
2, create a AViewController which will be used as subview. And I add a pickerView and a navigation bar into that view and adjust the view's height to around 260.
3, write code in that AViewController's class.
class APickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var pickerView:UIPickerView!
let dataList = [["a","b","c","d"]]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//pickerView.dataSource = self
//pickerView.delegate = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return dataList.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataList[component].count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return dataList[component][row]
}
4, write code in Main ViewController to add the AViewController's View as subview.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let pickerViewController = storyboard?.instantiateViewController(withIdentifier: String(APickerViewController.self)) as! APickerViewController
self.view.addSubview(pickerViewController.view)
self.view.bringSubview(toFront: pickerViewController.view)
pickerViewController.view.frame = CGRect(x: 0, y: self.view.frame.height - 300, width: self.view.frame.width, height: 300)
}
and also one question here actually I'm not that sure the difference.
A:
let pickerViewController = storyboard?.instantiateViewController(withIdentifier: String(APickerViewController.self)) as! APickerViewController
B:
let pickerViewController = APickerViewController()
What's the different of A and B ? If I do some #IBOutlet settings by Interface Builder will be affected or what ?
5, go and ... get weired ...
the function
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataList[component].count
}
sometime's get called many times and sometimes not get called.
and the data was not show in pickerView and sometimes only show row 1,2 and no others and if I flick up or down those 1,2 row data disappeared.
if anyone have a better solution of using pickerView as option popup window ?
Help.
Thanks
class EditViewController: UIViewController,UITextFieldDelegate,UIPickerViewDelegate{
var picker : UIPickerView = UIPickerView()
var toolBar : UIToolbar = UIToolbar()
#IBOutlet var txtFieldState: UITextField!
var stateArray = ["Andaman & Nicobar Island","Andhra Pradesh","Arunachal Pradesh","Assam","Bihar","Chandigarh","Chhattisgarh","Dadra & Nagar"]
override func viewDidLoad() {
super.viewDidLoad()
txtFieldState.delegate = self
}
func textFieldDidBeginEditing(textField: UITextField) {
if textField == txtFieldState{
txtFieldState.inputView = picker
txtFieldState.inputAccessoryView = toolBar
self.configurePicker()
}
}
func configurePicker()
{
picker.alpha = 1.0
picker.backgroundColor = UIColor(red:241/255.0, green:241/255.0, blue:241/255.0, alpha: 1.0)
picker.showsSelectionIndicator = true
picker.delegate = self
picker.selectedRowInComponent(0)
let screenRect = self.view.frame
let pickerSize = picker.sizeThatFits(CGSizeZero)
let x = screenRect.origin.x + (screenRect.size.width / 2) - (pickerSize.width / 2)
let pickerRect = CGRectMake(x,
screenRect.origin.y + (screenRect.size.height) - (pickerSize.height),
pickerSize.width,
pickerSize.height)
picker.frame = pickerRect
let toolbarSize = toolBar.sizeThatFits(CGSizeZero)
toolBar.frame = CGRectMake(x,pickerRect.origin.y, // right under the picker
pickerSize.width, // make them the same width
toolbarSize.height)
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
dropState = row
txtFieldState.text = "\(stateArray[row])"
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return stateArray[row]
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return stateArray.count
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
return 1
}
}
I haven't a whole lot of code, so I might as well copy it here.
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{
var buildings = ["BankBuilding", "Cinema" , "CornerShop", "Greg's House"]
#IBOutlet weak var buildText: UITextField!
var buildPickers:UIPickerView = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
buildPickers = UIPickerView()
buildPickers.delegate = self
buildPickers.hidden = true;
buildText.inputView = buildPickers
buildText.text = buildings[0]
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
println("Count: \(buildings.count)")
return buildings.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
println("creating title: \(buildings[row])")
return buildings[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
println("Selected: \(buildings[row])")
buildText.text = buildings[row]
buildPickers.hidden = true;
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
buildPickers.hidden = false
return false
}
}
The print statements are correct. For numberOfRows... and titleForRow it is printing the correct Strings.
But there is no prints for didSelectRow because, well, I can't select a row.
This is what I get:
You can ignore the Google Map in the background, that shouldn't interfere with the Picker View and is just set up in the StoryBoard.
The Grey window appears when I click on the textField but never shows any content. But the print statements say otherwise.
Does anyone know why this is the case?
Just add this line in your viewDidLoad method:
buildPickers.dataSource = self
And your code will be:
override func viewDidLoad() {
super.viewDidLoad()
buildPickers = UIPickerView()
buildPickers.delegate = self
buildPickers.dataSource = self
buildPickers.hidden = true;
buildText.inputView = buildPickers
buildText.text = buildings[0]
}
And it will show your data.
UPDATE:
It is not showing because you set it hidden in your viewDidLoad.
Just remove this line from your code:
buildPickers.hidden = true
Here is your working code:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate{
var buildings = ["BankBuilding", "Cinema" , "CornerShop", "Greg's House"]
#IBOutlet weak var buildText: UITextField!
var buildPickers:UIPickerView = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
buildPickers = UIPickerView()
buildPickers.delegate = self
buildPickers.hidden = true
buildText.delegate = self //set delegate for textField
buildText.inputView = buildPickers
buildText.text = buildings[0]
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
println("Count: \(buildings.count)")
return buildings.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
println("creating title: \(buildings[row])")
return buildings[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
println("Selected: \(buildings[row])")
buildText.text = buildings[row]
buildPickers.hidden = true;
}
//this method will call when you click on textField
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
buildPickers.hidden = false
return true
}
}
Is the delegate set on the text field? Are you getting the callback which you use to un-hide the picker?