I have a UIPickerView that when tapping the done button, keeps selecting the last option of the Array. I can tap on either the UITextField or a button I'm using that assigns the UITextField as the first responder. My code is as follows:
Edit. I should also mention that I'm using Xcode 11 GM Seed if that was to make a difference. I tested a clean version of the code shown below on a separate project with nothing else and it is displaying the same behavior.
#IBOutlet weak var sortTypeTextField: UITextField!
var selectedSortOption = String()
let sortOptions = [
USER_REVIEWS_SORT_OPTION_DATE,
USER_REVIEWS_SORT_OPTION_LIKES,
USER_REVIEWS_SORT_OPTION_DISLIKES
]
sortOptions above is an array of Strings located in a different file but for the purpose of this question I’ll add here:
let USER_REVIEWS_SORT_OPTION_DATE = "Date"
let USER_REVIEWS_SORT_OPTION_LIKES = "Number of Likes"
let USER_REVIEWS_SORT_OPTION_DISLIKES = "Number of Dislikes"
let DONE_TOOLBAR_BUTTON_TITLE = "Done"
I have a function setupUI which I call in viewDidLoad along with the value for the sortTypeTextField. The value is the first String in the array when the viewController first loads.
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
sortTypeTextField.text = sortOptions[0]
createSortPicker()
createPickerToolbar()
}
func createSortPicker() {
let sortPicker = UIPickerView()
sortPicker.delegate = self
sortTypeTextField.inputView = sortPicker
}
func createPickerToolbar() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: DONE_TOOLBAR_BUTTON_TITLE, style: .plain, target: self, action: #selector(dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
sortTypeTextField.inputAccessoryView = toolBar
}
#objc override func dismissKeyboard() {
view.endEditing(true)
}
I’m also using a button to display the UIPicker as shown here:
#IBAction func sortRatingsButtonWasTapped(_ sender: Any) {
sortTypeTextField?.becomeFirstResponder()
}
As shown below, I want for the sortTypeTextField value to change to the selected option but for some reason when tapping the Done button in the toolbar, the text shown is always the third String in the array regardless if I have chosen the first, the second or the third.
extension ReviewsViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
sortOptions.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return sortOptions[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedSortOption = sortOptions[row]
sortTypeTextField.text = selectedSortOption
}
}
It seems to be a bug in the simulator. I tested the my code above and the code provided by Abdul Karim Khan on my device and the work as they should. The label updates according to the option selected in the picker view.
This is how I created pickerView,
class ViewController: UIViewController {
#IBOutlet weak var selectaday: UITextField!
let days = ["monday","wednesday"]
var selectedDay: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createDayPicker()
}
func createDayPicker(){
let dayPicker = UIPickerView()
dayPicker.delegate = self
selectaday.inputView = dayPicker
}
}
extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return days.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return days[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedDay = days[row]
selectaday.text = selectedDay
}
}
Related
I am trying to set up 2 UIPickerViews in 1 view controller. I have not been able to find resources that solve my problem.
I have tried following the answer from Diavel Rider on How to use 2 UIPickerView's in one View Controller?. I got some errors from that. I have also tried adding tags but was not able to successfully do that. I am using Swift 4.
Here is the code of my view controller:
import UIKit
class FirstViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ foodTypeUIPickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var countrows : Int = nutritionPickerData.count
if pickerView == foodTypeUIPickerView { **[Error Here: "Binary operator '==' cannot be applied to operands of type '_' and 'UIPickerView'"]**
countrows = self.foodTypePickerData.count
}
return countrows
}
func pickerView(_ foodTypeUIPickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == nutritionUIPickerView { **[Error Here: "Binary operator '==' cannot be applied to operands of type '_' and 'UIPickerView'"]**
let titleRow = nutritionPickerData[row]
return titleRow
} else if pickerView == foodTypeUIPickerView { **[Error Here: "Binary operator '==' cannot be applied to operands of type '_' and 'UIPickerView'"]**
let titleRow = foodTypePickerData[row]
return titleRow
}
return ""
}
#IBOutlet weak var nutritionUIPickerView: UIPickerView!
#IBOutlet weak var foodTypeUIPickerView: UIPickerView!
var nutritionPickerData = ["Protein", "Fiber", "Iron", "Fat", "Sodium", "Calcium/Vitamin D", "Energy", "Carbohydrates", "Cholestorol"]
var foodTypePickerData = ["Fruits", "Vegetables", "Legumes and Beans", "Grain", "Meat", "Dairy"]
#IBAction func submitUIButton(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.nutritionUIPickerView.delegate = self
self.nutritionUIPickerView.dataSource = self
self.foodTypeUIPickerView.delegate = self
self.foodTypeUIPickerView.dataSource = self
}
}
I need to use 2 picker views in 1 view controller. How do I do this?
You are referencing a non-existent variable named pickerView. You should update the parameter name to pickerView to avoid issues.
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == foodTypeUIPickerView {
return self.foodTypePickerData.count
} else {
return self. nutritionPickerData.count
}
}
Make a similar change to the other delegate/data source methods.
You should separate your data sources and delegates and not put them inside your view controller. Set those as the delegate and datasource. Code written in swift 4.2 xcode 10.1
class ViewController: UIViewController {
#IBOutlet weak var foodPicker: UIPickerView!
#IBOutlet weak var nutritionPicker: UIPickerView!
var foodData = FoodData()
var nutritionData = NutritionData()
override func viewDidLoad() {
super.viewDidLoad()
foodPicker.delegate = foodData
foodPicker.dataSource = foodData
nutritionPicker.delegate = nutritionData
nutritionPicker.dataSource = nutritionData
}
#IBAction func actionButton(_ sender: UIButton) {
let food = foodPicker.delegate?.pickerView!(foodPicker, titleForRow: foodPicker.selectedRow(inComponent: 0), forComponent: 0)
let nutrition = nutritionPicker.delegate?.pickerView!(nutritionPicker, titleForRow: nutritionPicker.selectedRow(inComponent: 0), forComponent: 0)
print("You picked: \(food) and \(nutrition)")
}
}
class FoodData: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {
var foodTypePickerData = ["Fruits", "Vegetables", "Legumes and Beans", "Grain", "Meat", "Dairy"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return foodTypePickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return foodTypePickerData[row]
}
}
class NutritionData: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
var nutritionPickerData = ["Protein", "Fiber", "Iron", "Fat", "Sodium", "Calcium/Vitamin D", "Energy", "Carbohydrates", "Cholestorol"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return nutritionPickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return nutritionPickerData[row]
}
}
I would like to add a function in my app where the user has to choose a category from a UIPickerView and upon clicking a button, the program would open the view selected from the categories in the UIPickerView. For example, if one of the chosen options on the UIPickerView is "About Page", I would like to have a program that would open the "About Page" upon a click of the button.
This is what the UI would look like.
But instead of the states - I would have the categories, I'm not sure how to set the values in the UIPickerView and open specific views.
Implement UIPickerViewDelegate method and give each VC a stroryboard Identifier
var lastId:String?
var ids = ["secondVC","thirdVC"] // picker data source and identifier names
func pickerView(_ pickerView: UIPickerView,
didSelectRow row: Int,
inComponent component: Int) {
lastId = ids[row]
}
#IBAction func goClicked(_ sender:UIButton) {
if let id = lastId {
let vc = storyboard.instantiateViewController(withIdentifier:id)!
self.present(vc, animated: true, completion: nil) // or push
}
else {
// select a vc alert
}
}
If you want to create the picker view programmatically - which I recommend the most - this solution should work for you:
class MyViewController : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let pickerView = UIPickerView()
let titles = ["view1", "view2"]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
pickerView.delegate = self
pickerView.dataSource = self
view.addSubview(pickerView)
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return titles[row]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row == 0 {
let view1 = viewController1()
self.present(view1, animated: true, completion: nil)
}
if row == 1 {
let view2 = viewController2()
self.present(view2, animated: true, completion: nil)
}
}
}
class viewController1 : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
}
}
class viewController2 : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
}
}
hope that this works for you too ;)
I am building a simple app that has a PickerView with 3 selections that should link to 3 viewControllers each named FirstViewController, SecondViewController and ThirdViewController.
But I am getting this error
> NSInvalidArgumentException', reason: 'Receiver (<Scroller.ViewController: 0x7ff7b5e0b670>) has no segue with identifier 'SecondSegue'
I have three options in the picker and a button to go to that selection's viewController:
My code below works on first loading then crashes
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBAction func continueButtonPressed(_ sender: AnyObject) {
self.performSegue(withIdentifier: "\(chosenState)Segue", sender: nil)
print("no chance")
}
#IBOutlet weak var pickerView: UIPickerView!
var pickerData = ["First","Second","Third"]
var chosenState = ""
override func viewDidLoad() {
super.viewDidLoad()
print("Help")
pickerView.delegate = self
pickerView.dataSource = self
// 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.
}
// The number of columns of data
// The number of rows of data
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
// The data to return for the row and component (column) that's being passed in
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
}
//Called when the user changes the selection...
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
chosenState = pickerData[row]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
}
can anyone help me understand how to fix this ?
Have I named the Segues ok? They are all named the same - is that correct?
You have to set the segue identifier to second view controller as SecondSegue
It seems your SecondSegue to your second UIViewController has not been named properly.
Be careful, it is case sensitive, it must be named precisely SecondSegue. And after having changed the name, don't forget to validate your input with the return key.
I'm trying to make drop-down list where picker view is not visible until user clicks on textfield. Then picker view disappears after user makes selection from pickerView. Currently, the picker View does not show up at all when I click on textfield.
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var textBox: UITextField!
#IBOutlet weak var pickerView: UIPickerView!
var choices = ["SortBy:", "Date(ascending)", "Date(descending)","Calories Burned(descending)","Duration(descending)"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
self.view.endEditing(true)
return choices[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return choices.count
}
fun pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.textBox.text = self.choices[row]
self.pickerView.isHidden = true
print("hello")
}
func textFieldDidBeginEditing(TextField: UITextField){
if TextField == self.textBox {
self.pickerView.isHidden = false
TextField.endEditing(true)
}
}
override func viewDidLoad() {
self.pickerView.isHidden = true
super.viewDidLoad()
}
}
try this :
override func viewDidLoad() {
self.pickerView.isHidden = true
super.viewDidLoad()
self.textBox.delegate = self
self.pickerView.delegate = self
}
I can't figure out why I can't access this variable, see below, I want the value of sport result when it's clicked, however sportResult.selectedSport returns nil?
let sportPickerData = SportPickerData()
override func viewDidLoad() {
super.viewDidLoad()
sportPickerView.delegate = sportPickerData
sportPickerView.dataSource = sportPickerData
class SportPickerData: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {
var sports = ["Football", "Baseball", "Hockey", "Basketball"]
var selectedSport: String?
func numberOfComponentsInPickerView(yearPicker: UIPickerView) -> Int {
return 1
}
func pickerView(yearPicker: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return sports.count
}
func pickerView(yearPicker: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedSport = sports[row]
}
func pickerView(yearPicker: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return "\(sports[row])"
}
}
let sportResult = SportPickerData()
#IBAction func button(sender: UIButton) {
label.text = sportResult.selectedSport
}
sportResult its not a delegate or a data source of your picker view so its selectedSport property will never be initialized since its didSelectRow method will be never called. To get the selectedSport you have to get it from sportPickerData which is actually the delegate and data source of your picker
let sportResult = SportPickerData() // delete this line
#IBAction func button(sender: UIButton) {
label.text = sportPickerData.selectedSport
}