Jeremy Jeremy - 2 months ago 20
iOS Question

Swift - how to concatenate didSelectRow selections from UIPickerView

I have a two column picker (Miles and Tenths)

Picker seems to work well, but I cannot seem to work out how to concatenate the selections from the two columns i.e. if user selects 23 from first column and 6 from second column, I want to create an answer of "23.6"

At the moment, either column selection overwrites the previous selection.

BTW: I don't think I can append two strings because what happens if user selects the 10ths first?

let resetPickerData = [Array(0...99), Array(0...9)]

// returns the number of 'columns' to display.
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
return 2
}

// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int{
return resetPickerData[component].count
}

func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
return String(resetPickerData[component][row])
}

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
//var distance = ??
}

Answer

You'll need to keep track of the component selection separately like this then concant the strings:

var firstComponentString = ""
var secondCompoentString = ""

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
    if component == 0 {
        firstComponentString = String(resetPickerData[component][row])
    }
    else  if component == 1 {
        secondCompoentString = String(resetPickerData[component][row])
    }

    var displayString = "\(firstComponentString).\(secondCompoentString)"
}