key9060 key9060 - 3 months ago 11
Swift Question

Picker Views and if statements

I have created a successful pickerview using this tutorial:

Link to tutorial

I want to be able to do something different when each option is selected whereas most tutorials just show how to do one thing for all options e.g. putting the option text into a label.

This is the code I have attempting to do what I want. (I put in the print part to see if the code was being run and it wasn't.)

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row == 0 {
currentSpeedMeasurement = "MPH"
speed = speed * 2.23694
print("Testing")
}else if row == 1 {
currentSpeedMeasurement = "KPH"
speed = speed * 3.6
} else if row == 2 {
currentSpeedMeasurement = "M/S"
speed = locationManager.location!.speed
//speed = round(100 * speed)
}
}


Edit: Below is all of my code for the project. I am creating an app that shows the speed the person is travelling at.
I want the user to pick a speed measurement from the PickerView (named measurementPicker) e.g. MPH.

I want the switch to activate depending on what option the user selects using the switch statement.

I want the speed to then be displayed in a label (having been converted to the desired measurement) with the measurement afterwards. E.G. "Your speed: 10 MPH"

The switch doesn't seem to be running because the measurement is always m/s.

Please help!

Thanks

Answer

The code looks good, i think it will be better using switch

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    switch row {
    case 0:
        currentSpeedMeasurement = "MPH"
        speed = speed * 2.23694
        print("Testing")
    case 1:
        currentSpeedMeasurement = "KPH"
        speed = speed * 3.6
    default:
        currentSpeedMeasurement = "M/S"
        speed = locationManager.location!.speed
        //speed = round(100 * speed)
    }
}

why it's not working? i think you're missing setting delegate for the picker, do it through your storyboard

Setting delegate via storyboard

or via code:

@IBOutlet weak var pickerView: UIPickerView! {
        didSet{
            pickerView.delegate = self
            pickerView.dataSource = self
        }
    }

and it should work fine with you after.

Comments