How to use the selected value in UIPickerView - ios

New to this, trying to create a simple app where user selects a birth year and a corresponding variable is shown.
i'd like the #IBAction func get to get the variable birthYear from the UiPicker at the bottom. I set the datasource and delegate for UIPicker to viewcontroller in the connections inspector panel.
class ViewController: UIViewController,UIPickerViewDelegate {
var years = ["1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999"]
let nineOne = "24"
let nineTwo = "23"
let nineThree = "22"
let nineFour = "21"
let nineFive = "20"
let nineSix = "19"
let nineSeven = "18"
let zero = "17"
#IBAction func get(sender: AnyObject) {
if birthYear <= 1991
{
println(nineOne)
}
else if birthYear == 1992
{
println(nineTwo)
}else if birthYear == 1993{
println(nineThree)
}
else if birthYear == 1994{
println(nineFour)
}
else if birthYear == 1995{
println(nineFive)
}
else if birthYear == 1996{
println(nineSix)
}
else if birthYear == 1997{
println(nineSeven)
}
// current year minus 17
else if birthYear >= 1998 {
println(zero)
}
}
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 years.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{
return years[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var birthYear = years[row]
}

If you don't know how to continue, here are 2 tutorials:
Displaying the result with a UILabel: http://makeapppie.com/tag/uipickerview-in-swift/
Displaying the result in UITextField: http://asanhussain.blogspot.ca/2012/11/uipickerview-in-uiactionsheet-for-iphone.html
Pay attention to the implementation for
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
Also, for UITextField implementation, needs to assign UIPickerView to inputView of UITextField.
=====================================================================
This is for your follow-up. There're 3 minor things to be noticed in your code.
First, you should connect an IBOutlet of UIPickerView to this View Controller. In your code, you connect a IBAction called get (which I think it's not very good as a function name) for some other view component.
Second, you didn't assign the delegate of picker view to the current view controller. So those delegate methods won't be called.
Third, birthYear's type is String. It can't be compared to Int directly.
Here is the revised code that will work if you connect PickerView in your storyboard to this IBOutlet. Hope it helps.
import UIKit
class ViewController: UIViewController,UIPickerViewDelegate {
#IBOutlet var pickerView: UIPickerView!
var years = ["1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999"]
let nineOne = "24"
let nineTwo = "23"
let nineThree = "22"
let nineFour = "21"
let nineFive = "20"
let nineSix = "19"
let nineSeven = "18"
let zero = "17"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pickerView.delegate = self
}
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 years.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{
return years[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var birthYear = years[row]
self.printYear(birthYear)
}
func printYear(birthYearString: String) {
if let birthYear = birthYearString.toInt() {
if birthYear <= 1991
{
println(nineOne)
}
else if birthYear == 1992
{
println(nineTwo)
}else if birthYear == 1993{
println(nineThree)
}
else if birthYear == 1994{
println(nineFour)
}
else if birthYear == 1995{
println(nineFive)
}
else if birthYear == 1996{
println(nineSix)
}
else if birthYear == 1997{
println(nineSeven)
}
// current year minus 17
else if birthYear >= 1998 {
println(zero)
}
}
}
}

Related

Picker not outputting row data swift 3

I'm trying to write a color picker for a task app. When I try to add the task the picker never makes the changes to my 'picked' variable (declared on line 5) and will only print "blank" (line 7). I'm new enough to pickers that I can't see what I'm doing wrong. I'm fairly certain it has to do with the setup of my didSelectRow function (last function), because if the function were firing, it would still set something in the else statement, even if it's not the string I want, but it's not making any changes at all.
class SecondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var input: UITextField!
#IBOutlet weak var picker: UIPickerView!
var pickerData: [String] = [String]()
var picked: String = "blank"
#IBAction func addItem(_ sender: Any) {
print (picked)
if (input.text != "" && picked != "") {
list.append(input.text! as AnyObject)
if picked == "Red" {
colors.append(UIColor.red)
}
else if picked == "Orange" {
colors.append(UIColor.orange)
}
else if picked == "Yellow" {
colors.append(UIColor.yellow)
}
else if picked == "Green" {
colors.append(UIColor.green)
}
else if picked == "Blue" {
colors.append(UIColor.blue)
}
else if picked == "Purple" {
colors.append(UIColor.purple)
}
else if picked == "White" {
colors.append(UIColor.white)
}
input.text = ""
userDefaults.set(list, forKey: "tasks")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.picker.delegate = self
self.picker.dataSource = self
pickerData = ["Select a color", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponents(in 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) {
if row == 0 {
picked = ""
}
else {
picked = pickerData[row]
}
}
}
You forget argument label _
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

Having multiple Picker Views

I am trying to have multiple picker views in one single view in swift.
So far I have created 2 different textfields and I want both of them to have different picker views if I click on them. so let us say if click on textfield #1 it opens the array #1 and textfields #2 the second.
I have already looked up these questions but they do not really answer my question or solve my problem:
Multiple Picker Views on a single view
Creating Multiple Dynamic Picker Views
so my View Controller looks like this:
how my viewController should look
and this is my piece of code:
let pickOption = ["kg","lb"] //first array for first textfield
let ageOption = ["0-5", "6-10", "11-15"] //array for 2nd textfield
let pickerView = UIPickerView()
//picker View functions
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOption.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOption[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
weightTextField.text = pickOption[row]
}
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
weightTextField.inputView = pickerView
weightTextField.text = pickOption[0]
}
so as mentioned before, the first textfield opens up the array 'pickOption' and the second array opens up 'ageOption'
EDIT: 'weightTextField' ist the first textfield which opens up the first array(pickOption)
We can do it for multiple UITextField from single PickerView, with the help of UITextFieldDelegate
let pickOption = ["kg","lb"] //first array for first textfield
let ageOption = ["0-5", "6-10", "11-15"] //array for 2nd textfield
let pickerView = UIPickerView()
var currentTxtFldTag : Int = 10
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
weightTextField.tag = 10
ageTextField.tag = 20
weightTextField.delegate = self
ageTextField.delegate = self
weightTextField.inputView = pickerView
weightTextField.text = pickOption[0]
ageTextField.inputView = pickerView
ageTextField.text = ageOption[0]
// Do any additional setup after loading the view.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if currentTxtFldTag == 10
{
return pickOption.count
}
else
{
return ageOption.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if currentTxtFldTag == 10
{
return pickOption[row]
}
else
{
return ageOption[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if currentTxtFldTag == 10
{
weightTextField.text = pickOption[row]
}
else
{
ageTextField.text = ageOption[row]
}
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField.tag == 10 // WEIGHT OPTION
{
currentTxtFldTag = 10
}
else // AGE OPTION
{
currentTxtFldTag = 20
}
pickerView.reloadAllComponents()
return true
}
Output
Suppose that you have two pickerView controls: picker0 and picker1.
class HomeViewController: BasicViewController, UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
let numberArray = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180]
var areaArray = [String]()
#IBOutlet weak var picker0: UIPickerView!
#IBOutlet weak var picker1: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
// area //
for i in 0..<11 {
let str = "Area "
let localStr = NSLocalizedString(str + String(i), comment: "")
areaArray.append(localStr)
}
}
// MARK: - Campaign duration & area
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == picker0 {
return numberArray.count
} else {
return areaArray.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == picker0 {
return String(numberArray[row]) + " pieces"
} else {
return areaArray[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == seventhPicker {
} else {
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
weightTextField.inputView = pickerView
}
let pickOption = ["kg","lb"] //first array for first textfield
let ageOption = ["0-5", "6-10", "11-15"] //array for 2nd textfield
let pickerView = UIPickerView()
//picker View functions
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if weightTextField1.tag == 1 {
return pickOption.count
} else if weightTextField2.tag == itemPicker {
return ageOption.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if weightTextField1.tag == 1 {
return pickOption[row]
} else if weightTextField2.tag == 1 {
return ageOption[row]
}
return 0
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if weightTextField1.tag == 1 {
weightTextField1.text = pickOption[row]
} else if weightTextField2.tag == 1 {
weightTextField2.text = ageOption[row]
}
}
////set delegate
func textFieldDidBeginEditing(textField: UITextField!) { //delegate method
if textField == weightTextField1
{
weightTextField1.atg = 1;
weightTextField2.atg = 0;
}
else if textField == weightTextField2
{
weightTextField1.atg = 0;
weightTextField2.atg = 1;
}
picker.reloadAllComponents()
}
}

Two UIPickerViews and different combinations lead to different photos

I am very new to swift Xcode and would like some help on UIPickerView.
I am trying to create two UIPickerViews, one called "From" and one called "To". "From" contains A, B and "To" contains B, C
Basically, if "From" is A and "To" is B then a Photo of car will appear on the same viewController.
if "From" is B and "To" is B then a photo of strawberry will appear and so on.
Can anyone give me any hints on how to do this? I've only managed to create the first UIPickerView.
import UIKit
class ViewController: UIViewController,UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet var Picker1:UIPickerView!
var Array = ["A","B","C"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
Picker1.delegate = self
Picker1.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Array[row]
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Array.count
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
}
var savedVal1 = "" as String
var savedVal2 = "" as String
var array1 = NSArray()
var array2 = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
Picker1.delegate = self
Picker1.dataSource = self
Picker1.tag = 1
Picker2.delegate = self
Picker2.dataSource = self
Picker2.tag = 2
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 1 {
return array1[row]
}
else{
return array2[row]
}
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 1 {
return array1.count
}
else{
return array2.count
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
if pickerView.tag == 1 {
savedVal1 = array1[row]
// compare 2 values here & then take steps which fulfill your criteria.
}
else{
savedVal2 = array2[row]
//compare 2 values here & then take steps which fulfill your criteria.
}
}
Hope it helps.
Where is your PickerView2?
#IBOutlet var Picker2:UIPickerView!
In viewdidload load as you done
Picker1.delegate = self
Picker1.dataSource = self
If you are using same data source or different please check the picker view in UIPickerViewDelegate, UIPickerViewDataSource method like
If (Picker1) {
} else if (Picker2) {
}

Acces to viewController from a pickerView

On a sight I have a PickerView and a button. Depending on the choice in the pickerview (I have 4 lines) I would like clicking on a button to go on a specific view. Now, whatever my choice is, I'm always on the same view (saline). Below is my code of the controller. If anyone can help me understand my mistake?
import UIKit
class SommaireGeneralViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var picker: UIPickerView!
var PlacementAnswer = 0
var liste = ["Sommaire général", "Région Est", "Région Ouest", "Région Sud", "Région Nord"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.picker.delegate = self
self.picker.dataSource = self
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return liste[row]
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return liste.count
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData = liste[row]
let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 10.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()])
return myTitle
}
#IBAction func Voir(sender: AnyObject) {
if (PlacementAnswer == 0) {
self.performSegueWithIdentifier("Saline", sender: self)
} else if (PlacementAnswer == 1){
self.performSegueWithIdentifier("1", sender: self)
return
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
PlacementAnswer = row
}
func prepareForSegue(id: UIStoryboardSegue, sender: AnyObject?) {
if "Saline" == id.identifier {
}
else if "1" == id.identifier {
}
}
}
Hello, finally it's working, I put the code that can be used for others.
Cheers and thank you again for the info
import UIKit
class SommaireGeneralViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var picker: UIPickerView!
enum ActionSheetTag: Int {
case ActionSheet0
case ActionSheet1
}
var PlacementAnswer = Int()
let liste = ["Sommaire général", "Région Est", "Région Ouest", "Région Sud", "Région Nord"]
override func viewDidLoad() {
super.viewDidLoad()
self.picker.delegate = self
self.picker.dataSource = self
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return liste[row]
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return liste.count
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let titleData = liste[row]
let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 10.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()])
return myTitle
}
#IBAction func Voir(sender: AnyObject) {
if (PlacementAnswer == 0) {
self.performSegueWithIdentifier("Saline", sender: self)
} else if (PlacementAnswer == 1){
self.performSegueWithIdentifier("Autre", sender: self)
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let tag = ActionSheetTag(rawValue: row) {
switch tag {
case .ActionSheet0:
PlacementAnswer = 0
case .ActionSheet1:
PlacementAnswer = 1
}
}
}
}
You tried tag and enum? If your answer is no, try this and return the output to me.
enum ActionSheetTag: Int {
case ActionSheet1
case ActionSheet2
}
.
.
.
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let tag = ActionSheetTag(rawValue: pickerView.tag) {
switch tag {
case .ActionSheet1:
PlacementAnswer = 0
case .ActionSheet2:
PlacementAnswer = 1
}
}
}
Hope it helps.

How to navigate between two viewcontrollers using a UIPickerview

I am trying to navigate between two viewcontrollers using a UIPickerview, so i first learned how to use didSelectRow to change the title of a label and then i tried using some code to navigate to another viewcontroller but that didn't work.
The code that i used was:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet var label: UILabel!
#IBOutlet var pickerView: UIPickerView!
var food = ["hello", "hi", "hey"]
var placementAnswer = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pickerView.delegate = self
pickerView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return food.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return food[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
placementAnswer = row
}
#IBAction func labelChanged(sender: UIButton) {
if (placementAnswer == 0){
}else if (placementAnswer == 1){
let view2 = self.storyboard?.instantiateViewControllerWithIdentifier("view2") as! ViewController2
self.navigationController?.pushViewController(view2, animated: true)
}else if (placementAnswer == 2){
}
}
}
As paranoidcoder pointed out I'm not sure your labelChanged method is getting called, which could be the problem with your existing code.
I'm assuming you want to change the view controller after a certain row is selected in the picker view. Putting the if statement to change views in didSelectRow would make the most sense in that case.
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
placementAnswer = row // unnecessary variable
if (placementAnswer == 0){}
else if (placementAnswer == 1)
{
let view2 = self.storyboard?.instantiateViewControllerWithIdentifier("view2") as! ViewController2
self.navigationController?.pushViewController(view2, animated: true)
}
else if (placementAnswer == 2) {}
}

Resources