Swift: How to set a default Value of a UIPickerVie

2019-01-22 07:00发布

How do I set the starting row of the picker view in Swift? I see there is a code for Objective C, but I don't understand it. If anyone could explain how I can translate the Objective C code into Swift that would also be fantastic !

Thanks

3条回答
冷血范
2楼-- · 2019-01-22 07:34

Default value selected in pickerview in swift 3

If Your array like bellow

let pickerArray  = [
        ["displayValue":"--Select--" as AnyObject,"id":"" as AnyObject],
        ["displayValue":"Jame" as AnyObject,"id":"100" as AnyObject],
        ["displayValue":"Enamul" as AnyObject,"id":"201" as AnyObject]
    ]

Just add bellow line for default selected in pickerview

 pickerViewTextField.text  = pickerArray[0]["displayValue"] as! String
查看更多
成全新的幸福
3楼-- · 2019-01-22 07:50
@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)
查看更多
做自己的国王
4楼-- · 2019-01-22 07:51

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!

查看更多
登录 后发表回答