Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a default value for UIPickerView in Swift?

How do I set the starting row of the picker view in Swift?

I see there is a similar question for Objective-C, but I don't understand the code.

like image 538
KML Avatar asked Sep 18 '14 16:09

KML


3 Answers

This is the code I have used in one of my apps:

// Declare the outlet to the picker in your storyboard
@IBOutlet var myPicker: UIPickerView!

//...

override func viewDidLoad() {
//...
    myPicker.selectRow(row, inComponent: 0, animated: true)
}

Obviously, replace row and 0 with whatever values you want.

Hope this Helps!

like image 106
mtaylor Avatar answered Oct 20 '22 11:10

mtaylor


@IBOutlet weak var mPicker: UIPickerView!
var items: [String] = ["NoName1","NoName2","NoName3"] // Set through another ViewController
var itemAtDefaultPosition: String?  //Set through another ViewController

//..
//..

var defaultRowIndex = find(items,itemAtDefaultPosition!)
if(defaultRowIndex == nil) { defaultRowIndex = 0 }
mPicker.selectRow(defaultRowIndex!, inComponent: 0, animated: false)
like image 14
Jitendra Kulkarni Avatar answered Oct 20 '22 13:10

Jitendra Kulkarni


SWIFT 5

The function "SetDefaultValue" will position the pickerView on the desired string by finding the item position in the pickerData which is used to populate the picker view. In this example it will be "item 2"

var pickerView = UIPickerView()
var pickerData = ["item 1","item 2","item 3","item 4","item 5"]
var defaultItem = "item 2"

func setDefaultValue(item: String, inComponent: Int){
 if let indexPosition = pickerData.firstIndex(of: item){
   pickerView.selectRow(indexPosition, inComponent: inComponent, animated: true)   
 }
}
like image 5
STerrier Avatar answered Oct 20 '22 12:10

STerrier