How to store data from a picker view in a variable when a button is pressed?

有些话、适合烂在心里 提交于 2019-12-08 08:43:08

问题


I have a picker view with one component that I populated with an array of data. When the user presses a button, I want the selected data in that row to be stored in a variable so that I can send it to another view controller using a segue, where it will be displayed in a label. The only part I'm having trouble with is actually getting that data to be stored in order to be used somewhere else. I know that using a datePicker, I can do something like this to do what I want:

@IBAction func buttonPressed(sender: AnyObject) { var chosenDate: NSDate = self.datePicker.date }

This will store the date selected by the user in the var chosenDate, which is what I want for my pickerView when a button is pressed. I'm aware also that I can get that data in a pickerView using

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

The only problem with this is that it selects the data every single time a user changes the value, and it doesn't allow me to store the data in a variable outside the function for me to use it in my @IBAction func buttonPressed method. Thanks in advance!


回答1:


Alright, after trying different things I finally came up with a solution to my problem. It might not be what the more experienced developers do but it worked for me just like I wanted. Here is what I did:

@IBAction func saveButtonPressed(sender: AnyObject) {

    var chosen = pickerView.selectedRowInComponent(0)
    var chosenString = arrayPopulatingThePickerView[chosen]

}

I only have one component in the pickerView i need therefore when the button is pressed I store the row number of the component 0 in a variable, then I store the string in another variable by making it equal to the array I used to populate my picker view. I retrieve the row by passing it the chosen variable.




回答2:


You can create a function to store this date using NSUserDefaults. This way you can access it everywhere and anytime (even after closing the app).

func saveChosenDate(date:NSDate){
    NSUserDefaults.standardUserDefaults().setObject(date, forKey: "chosenDate")
    NSUserDefaults.standardUserDefaults().synchronize()
}

to load it:

func loadChosenDate()-> NSDate{
    return NSUserDefaults.standardUserDefaults().objectForKey("chosenDate") as NSDate
}

to delete/reset the value of it:

NSUserDefaults.standardUserDefaults().removeObjectForKey("chosenDate")
NSUserDefaults.standardUserDefaults().synchronize()

save it

@IBAction func buttonPressed(sender: AnyObject) {
    saveChosenDate(datePicker.date)
}

load it

let myDate = loadChosenDate()


来源:https://stackoverflow.com/questions/27770041/how-to-store-data-from-a-picker-view-in-a-variable-when-a-button-is-pressed

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