Search code examples
iosswiftuipickerview

Create two arrays and then use them in a third array used as data for a two spinner uipickerview


Hi I'm trying to create my first IOS app which uses a uiPickerView with two spinners.

From various tutorials I found that the picker data was defined so:

var pickerData = [["value1","value2", "value3"],["valueA", "valueB"]]

As I have a number of values I thought I would create them dynamically

The code I have is:

var poundValues = [String]()
var penceValues = [String]()

for var indexP:Int = 0; indexP < 100; indexP += 1 {
    poundValues.append("£ \(indexP)")
}

for var pindex:Int = 0; pindex < 100; pindex += 1 {
    penceValues.append(".\(pindex)")
}

let pickerData = [poundValues,penceValues]

Unfortunately I get compiler error and I can't figure out how to correct. The first error occurs on both the "for var" lines...Consecutive declarations on a line must be separated by ';' but I do have ;s in place. The second is on the "let pickerData" line...'ViewController.Type' does not have a member named 'poundValues'

Also in the penceValues I'd like to pad single digits with a leading 0 so that the spinner displays .00 .01 .02 .... .09 .10 .11 etc.

Any help appreciated.


Solution

  • The code you provided compiles fine as is, although you can save a second loop since both for loops iterate over the same indices. Also, below is the formatting to pad your single digits.

    var poundValues = [String]()
    var penceValues = [String]()
    
    for var indexP:Int = 0; indexP < 100; indexP += 1 {
        poundValues.append("£ \(indexP)")
        penceValues.append(NSString(format: ".%02d", indexP) as String)
    }
    
    let pickerData = [poundValues, penceValues]
    

    It would be helpful to see your UIViewController subclass in its entirety to help with the build errors you are seeing.