Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UIPickerView with multiple components in swift

Hi there I have been trying to get this working for ages with no success so apologies if this seems easy for you guys.

I want to use a 3 wheel UIPickerView - The 1st wheel didSelectRow value will be used to change the array for the remaining two wheels but they will be the same as it is a conversion app.

It seems to throw me an error up when populating the wheels saying that Anyobject is not identical to String. I cannot see anything wrong but I know it is something basic I have missed.

Any pointers would be much appreciated.

Motty.

//  ViewController.swift
//  picker test

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var picker1Label: UILabel!
    @IBOutlet weak var picker2Label: UILabel!

    @IBOutlet weak var bigPicker: UIPickerView!

    var wheelContents = []
    var length = ["metres","feet","yards","inches","mm","cm","miles"]
    var volume = ["m3","US Gall","Imp Gall","Barrels", "cubic FT","litres"]
    var conType = ["length","volume"]


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        wheelContents = [conType,length,length]

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    //For main selection of type of conversion
    // returns the number of 'columns' to display.
    func numberOfComponentsInPickerView(bigPicker: UIPickerView) -> Int{

        return wheelContents.count

    }

    // returns the # of rows in each component..
    func pickerView(bigPicker: UIPickerView, numberOfRowsInComponent component: Int) -> Int{

        return wheelContents[component].count


    }

    func pickerView(bigPicker: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{

        return wheelContents[component][row]

    }
}
like image 810
Stuck Beginner Avatar asked Oct 19 '22 16:10

Stuck Beginner


1 Answers

You need to tell Swift that your wheelContents array is an array of array of String:

var wheelContents:[[String]] = []

If you don't explicitly give wheelContents a type, Swift infers it to be NSArray which is what is giving you problems.

like image 91
vacawama Avatar answered Oct 22 '22 20:10

vacawama