ahmed ahmed - 1 month ago 26
iOS Question

Picker View Swift

I have a picker view that needs to be presented when UIButton is pressed. The text of the UIButton will change to the text of selected row. But how do I initiate the picker view for a button?

func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}

override func viewDidLoad() {
super.viewDidLoad()

picker.delegate = self
picker.dataSource = self

}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return CountryData.count
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
CountryButton.setTitle(CountryData[row], for: .normal)
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return CountryData[row]
}

@IBAction func Country(_ sender: AnyObject) {

CountryButton.inputView == picker

}


This won't work

Answer

Note: when you set the action method, be sure to set the sender to the type of control that's invoking the action, the UIButton or the UIPickerView or whatever. Don't leave it as AnyObject.

It's not completely clear to me what you're trying to do. You say that the picker view needs to change when you press a button, then you say that the text of the button needs to change to the row selected in the picker view.

Are you trying to get the text of the button to change when you select something in the picker view? Or are you trying to instantiate a new picker view when you press the button.

If you're trying to change the text of the button when you select a row in the picker view, then you want to add an onChanged() action method for the picker view and change the button's text in that method.

@IBAction func pickerChanged(_ sender: UIPickerView) {
    button.setTitle("New text", for: UIControlState)
}

An easy way to present a new picker view when a button is pressed is to put the picker view in a stack view and set its hide property. Then the button's onPress() method can unhide the picker view in the stack view.

@IBAction func onPress(_ sender: UIButton) {
    if weWannaShowthePicker {
        pickerStack.arrangedSubviews[pickerPosition].isHidden = false
    } else { // hide it
        pickerStack.arrangedSubviews[pickerPosition].isHidden = true
    }
}