benpalmer661 benpalmer661 - 3 years ago 112
Swift Question

get string value from UIPickerView selected string value from array? (swift/xcode)

I have a pickerview in my table view with two selections Male and Female

these are in the array.

var MaleFemalePickerViewArray = ["Male","Female"]


how to i get the selected string value?

to go

let selectedGender = "male"


as then i want to go
place the string value into firebase

like so

self.ref.child("Person's Account User").child(userID!).updateChildValues(["Gender": selectedgender])

Answer Source

The UIPickerViewDelegate (documented here) has the method pickerView(_:didSelectRow:inComponent:) (documented here)

That method is called when the user selects an item in your UIPickerView and gives your an index to the row selected by the user.

You can use that index to get the right element from your datasource (MaleFemalePickerViewArray in your case).

So:

  1. set the delegate property of your UIPickerView to be your class
  2. implement didSelectRow
  3. bingo :)

You could do something along the lines of:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    guard row < MaleFemalePickerViewArray.count else {
        return
    }

    let selectedGender = MaleFemalePickerViewArray[row].lowercased()

    //insert into firebase or do what ever you please :)
}

Update

Glad it worked...fell free to mark the answer as accepted :)

You ask:

...to go to the next view controller i want to guard that the have chosen a gender as at the moment in the VC it appears to be on "male" but it doesnt load to firebase , so i was thinking putting an empty string in the array and saying if selectedgender.text = "" (empty string) alert the user " please select a gender"

Why not use an optional for this?

If you "move" your selectedGender out as an optional on your class like so.

var selectedGender: String? = nil

and then set that in your didSelectRow: like so:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    guard row < MaleFemalePickerViewArray.count else {
        return
    }

    selectedGender = MaleFemalePickerViewArray[row].lowercased()
    //insert into firebase or do what ever you please :)
}

Then you can do a check when you attempt to go to the next page, something like:

func toNext() {
    if selectedGender == nil {
        //The user has not selected a gender, so show an alert and stay on this page
    } else {
        //Onwards
    }
}

That way you won't have to use an extra - not needed and irrelevant for your model - value in your array

Hope that helps you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download