How to store data from a picker view in a variable

2019-05-30 19:22发布

问题:

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()