pickerView in Swift does not display data - ios

This seems too simple to qualify as a post, but I've been stuck on this issue for longer than I'd like. The pickerView does not display the array [durations]. When run, the simulator is just the empty field. The code was copied directly from the UI class, yet it seems to be missing something.
class FirstViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var durationPicker: UIPickerView!
var durations = ["72 hours", "24 hours", "6 hours", "2 hours", "20 minutes"]
var durationsValue = [72.0, 24.0, 6.0, 2.0, 0.329]
var itemSelected: String = ""
var selectedDuration: Double = 0.0
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.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 5
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return durations[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
itemSelected = durations[row]
selectedDuration = durationsValue[row]
}
}

You need to set the delegate and the datasource inside viewDidLoad()
durationPicker.delegate = self
durationPicker.dataSource = self
Or just connect your picker delegate and datasource using Xcode interface

I suggest watching this video. This lady does an excellent job explaining various iOS-related topics.
https://www.youtube.com/watch?v=MdXmIViD17U
The issue that jumps out at me is you've got arrays specified at the top. Rather than hard-code values in, you should use return yourArray.count to return Ints.

Related

Saving UIPickerView Data to Parse

I have a UIPickerView I need to save the users selection to Parse. I've tried a million different things and it just leaves my column blank. Any ideas what I am doing wrong? The information is just not saving to Parse, I know the UIPicker works though because the label updates. I have searched google and stack and can't see anything wrong with my code?
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var pickerView: UIPickerView!
#IBOutlet weak var pickedLabel: UILabel!
var pickerDataSource = ["Car", "Bus", "Train", "Plane", "Boat"]
override func viewDidLoad() {
super.viewDidLoad()
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.pickerDataSource.count;
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return self.pickerDataSource[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
PFUser.currentUser()?["PickerColumn"] = self.pickerDataSource[row];
self.pickedLabel.text = "Your choice: \(self.pickerDataSource[row])"
PFUser.currentUser()?.saveInBackground()
}
I've also tried this:
var pickerSave: String?
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
pickerSave = pickerDataSource[row]
self.pickedLabel.text = "Your choice: \(self.pickerDataSource[row])"
}
#IBAction func next(sender: AnyObject) {
PFUser.currentUser()?["pickerColumn"] = pickerSave
self.performSegueWithIdentifier("next", sender:self)
PFUser.currentUser()?.saveInBackground()
}
If your label is updating then your picker is fine. You issue is the PFUser class. Is PFUser.currentUser() returning a dictionary as you expect? after you set "pickerColumn" can you print out its value on the console?
Does the following work:
PFUser.currentUser()?["pickerColumn"] = "1"
PFUser.currentUser()?.saveInBackground()
Those specific lines are what is breaking.
So It looks like you are trying to save the value from the picker into the parse _User class. I wouldn't recommend saving it there anyway. Im assuming you are using a mongoDB and this is a schema issue. So what I would do is make a new class for storing this data.
I would declare it like so.
var pickerData = PFObject(className:"PickerData")
#IBAction func next(sender: AnyObject) {
pickerData["user"] = PFUser.current()?
pickerData["data"] = self.pickedLabel.text
pickerData.saveInBackground()
}

UIPickerView "didSelectRow" selection with button leading to url

I have a picker set up and want to have the user make a selection then tap a button which leads to a url. This is what I have so far:-
class PickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var picker: UIPickerView!
#IBOutlet weak var label: UILabel!
var url = NSURL(string: "http://www.google.com")
var pickerData: [String] = [String]()
var pickerSites: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.picker.delegate = self
self.picker.delegate = self
pickerData = ["Google", "Facebook"]
pickerSites = ["http://www.google.com", "http://www.facebook.com"]
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
label.text = pickerSites[row]
}
siteBtn.addTarget(self, action: "didTapSite", forControlEvents: .TouchUpInside)
#IBAction func sitesBtn(sender: AnyObject) {
UIApplication.shared().openURL(NSURL(string: "http://www.google.com")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I've connected the "siteBtn" to a button on the screen. The picker and text label were working fine until I added the code for the button. I'm not sure if I've put the button code in the correct place. I know that I need the button to connect with the picker "didSelectRow" and that the "pickerData" list needs to correlate to the "pickerSites" list but I'm stuck.
Any help would be much appreciated.
this is the minimal setup you need. feel free to ask if anything is unclear:
// outlet to the pickerview
#IBOutlet weak var picker: UIPickerView!
// datasource
let pickerData = ["Google", "Facebook"]
let pickerSites = ["http://www.google.com", "http://www.facebook.com"]
// pickerview datasource methods
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
// pickerview delegate method
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
}
// ibaction for button tap
#IBAction func goToURLButtonTapped(sender: UIButton) {
let selectedSite = pickerSites[picker.selectedRowInComponent(0)]
UIApplication.sharedApplication().openURL(NSURL(string: selectedSite)!)
}

Swift: fatal error: unexpectedly found nil while unwrapping an Optional value when initializing UIlabel value

I'm pretty new to swift (I usually code in Java and C++), and I'm building my first ios app.
In this app, I'm trying to create a picker view, and the problem is when I'm trying to set the initial value of the label point to the first item in the picker view (array) it pops up the error
"fatal error: unexpectedly found nil while unwrapping an Optional
value"
Here is my code I'm working
class ViewController: UIViewController, UIPickerViewDelegate{
#IBOutlet var usertypeLabel: UILabel!
#IBOutlet var Picker: UIPickerView!
var usertype_array = ["patient","nurse"]
//var usertype: String!
override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
super.viewDidLoad()
usertypeLabel.text = usertype_array[0] //THIS IS WHERE THE ERROR OCCURS
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return usertype_array.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{
return usertype_array[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
var rowselected = usertype_array[row]
usertypeLabel.text = rowselected
}
}
Any idea why the error happens? Note that it stills runs if I delete that line of code. Thanks.
You are missing UIPickerViewDataSource and add it here:
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource
And in your viewDidLoad method add this:
Picker.dataSource = self
Picker.delegate = self
And here is your full working code:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{
#IBOutlet var usertypeLabel: UILabel!
#IBOutlet var Picker: UIPickerView!
var usertype_array = ["patient","nurse"]
//var usertype: String!
override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
super.viewDidLoad()
Picker.dataSource = self
Picker.delegate = self
usertypeLabel.text = usertype_array[0] //THIS IS WHERE THE ERROR OCCURS
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return usertype_array.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{
return usertype_array[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
var rowselected = usertype_array[row]
usertypeLabel.text = rowselected
}
}
If your outlet is correct it will work fine.
Check THIS sample for more Info.

Picker view does not return always the right value

I've defined a picker which does not return always the right value. Sometimes it just works but most of the time when I pick the item pickerView returns the wrong value.
I did associate the outlet delegate to the view controller and am using the following code:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate {
var categories = ["animals", "profession", "sea_animals", "food", "tools", "misc", "all"]
var cat: String = ""
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.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
println("cat size: \(categories.count)")
return categories.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{
println("cat: \(categories[row])")
return categories[row]
}
}
it works sometime but it is not reliable.
Any idea what I do wrongly?
Thanks!
I found the problem.
There is a function for selecting the row :)
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)

unexpected build error in Xcode

I'm attempting to build an iOS app in Xcode v6.2 using swift as a little personal project. So far I've cobbled together bits from my own research, however the following code throws an error when I try to build. Building full apps in swift is well out outside my knowledge scope so I'm hoping it's something obvious that someone can kindly guide me in the right direction.
The purpose is simply to populate a picker view, so I'm not in any way bound to the code if there is some simpler logic.
Here is the code:
import UIKit
import iAd
import QuartzCore
class ViewController: UIViewController, ADBannerViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate{
#IBOutlet weak var yearPicker: UIPickerView!
#IBOutlet weak var yearLabel: UILabel!
let listView = ["2013", "2014", "2015"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
println("Entering super.viewDidload() function")
yearPicker.delegate = self
yearPicker.dataSource = self
}
//Data Sources
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return listView.count
}
//Delegates
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return listView[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
yearLabel.text = listView[row]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The error I'm receiving is:
fatal error: unexpectedly found nil while unwrapping an Optional value
and it the following line is highlighted in the IDE:
yearPicker.delegate = self
If there's anything else that might help please let me know.
So I ended up starting again, creating the connection by ctrl + dragging into the editor to create the #IBOutlet connection.
I then removed the .delegate and .dataSource methods because I received an error stating that yearPicker did not have those members. So now I'm left with this code which works perfectly :)
Thanks to Abizern for putting me on the right track.
import UIKit
import iAd
import QuartzCore
class ViewController: UIViewController, ADBannerViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate{
#IBOutlet var yearPicker: [UIPickerView]!
#IBOutlet weak var yearLabel: UILabel!
let listView = ["2013", "2014", "2015"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//Data Sources
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return listView.count
}
//Delegates
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return listView[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
yearLabel.text = listView[row]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Resources