How can I get the selected value in the real-time, when I'm scrolling the UIPickerView

家住魔仙堡 提交于 2019-12-13 03:59:09

问题


For example, in this image, when I'm scrolling the UIPickerView to 2012 9 28, what I want is that the text of the black label will change into 2012 9 28 at the same time without pressing any buttons like the Done button

I’m using UIPickerView, I can get the selected data before, I can also put the data into label by clicking a Done button, but I cannot put the data into the label when I’m scrolling.

and In a general situation, My question is that when I Scroll the UIPickerView, how can I get the data which is selected in real time

could anyone help me ? ObjectiveC solution is OK, Swift solution is better for me, Thank you so much


回答1:


It is unclear if you are using a UIPickerView or a UIDatePicker.

For UIPickerView you need to implement the UIPickerViewDelegate. Make sure that delegate is added to your ViewController declaration and make sure in Storyboard to connect the delegate of the UIPickerView control to your view controller. Then implement this function:

func pickerView(_ pickerView: UIPickerView, 
        didSelectRow row: Int, 
         inComponent component: Int) {

}

For UIDatePicker you need to connect the action of the UIDatePicker in Storyboard to an @IBAction function in your view controller or else connect it in code using the addTarget function:

myDatePicker.addTarget(self, action: #selector(self.respondToPicker, for: .valueChanged), 



回答2:


Let me suppose that you are using UIDatePicker, in that you can control the action using UIControlEventValueChanged

Like,

datePickerView?.addTarget(self, action: #selector(self.valueChanged(_:)), for: UIControlEvents.valueChanged)

the valueChanged() will be,

func valueChanged(_ datePicker: UIDatePicker) {
    let selectedDate = datePicker.date as NSDate
    print(selectedDate)
}

and if you are using UIPickerview then,

titleForRow: will gave you scrolling value

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
    print("your value")
}

and didSelectRow: will give you selected value

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
     print("your value")
}


来源:https://stackoverflow.com/questions/47771214/how-can-i-get-the-selected-value-in-the-real-time-when-im-scrolling-the-uipick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!