Swift: How to set a default Value of a UIPickerView with three components in Swift?

前端 未结 4 1669
一向
一向 2020-12-13 18:03

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 th

相关标签:
4条回答
  • 2020-12-13 18:34
    @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)
    
    0 讨论(0)
  • 2020-12-13 18:37

    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)   
     }
    }
    
    0 讨论(0)
  • 2020-12-13 18:43

    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!

    0 讨论(0)
  • 2020-12-13 18:52

    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
    
    0 讨论(0)
提交回复
热议问题