How do I set the initial Picker value that I set to input UITextField in Swift?

Asked 2 years ago, Updated 2 years ago, 38 views

I understand how to use Picker to enter the UITextField, but I am having trouble setting the initial value.

The source code will tap Button in other Views and transition to the ConditionViewController as outlined below.At that time, I would like to set the initial value to Pcker depending on the type of Button I tapped in the previous View.The current source code works without any errors.I have omitted the code that does not appear to be relevant to the following.

After searching on the Internet and github,
How do I set the initial value in Pcker without TextField? It's easy to find, but I'm at a loss because I can't find any examples of using TextField.

Please let me know what to do.

Environment
Xcode 7.1

Code

class ConditionViewController:UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{

@IBOutlet weak var location: UITextField!
let locationPickerView=UIPickerView()
override func viewDidLoad(){
    super.viewDidLoad()
    _setPcker()

}

func_setPcker(){
    locationPickerView.delegate=self
    locationPickerView.dataSource=self
    // I think I'm setting the initial value here, but it's not set.
    locationPickerView.selectRow(0, inComponent:0, animated:false)
    location.inputView = locationPickerView
}

ios swift xcode

2022-09-30 16:04

1 Answers

We tested it using the following sources, but we were able to set the initial value without any problems.Could there be something else? (Check Xcode 7.2/iOS 9)

import UIKit

classViewController:UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var location: UITextField!
    let locationPickerView=UIPickerView()

    override func viewDidLoad(){
        super.viewDidLoad()

        _setPcker()
    }

    func_setPcker(){
        locationPickerView.delegate=self
        locationPickerView.dataSource=self

        // I think I'm setting the initial value here, but it's not set.
        locationPickerView.selectRow(5, inComponent:0, animated:false)
        location.inputView = locationPickerView
    }

    func numberOfComponentsInPickerView (pickerView:UIPickerView) - > Int {
        return1
    }

    funcpickerView (pickerView:UIPickerView, numberOfRowsInComponent component:Int) - > Int {
        return 10
    }

    funcpickerView (pickerView:UIPickerView, widthForComponent component:Int) - > CGFloat{
        return120
    }

    funcpickerView (pickerView:UIPickerView, titleForRow:Int, forComponent component:Int) - > String?{
        return "Item\(row)"
    }

    funcpickerView(pickerView:UIPickerView, didSelectRowrow:Int, inComponent component:Int){
        location.text = "Item\(row)"
    }
}

The runtime screen looks like this.

The screen with UIPickerView


2022-09-30 16:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.