按下按钮时如何在变量中存储选择器视图中的数据? [英] How to store data from a picker view in a variable when a button is pressed?

查看:88
本文介绍了按下按钮时如何在变量中存储选择器视图中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择器视图,其中包含一个用数组数组填充的组件。当用户按下按钮时,我希望该行中的所选数据存储在变量中,以便我可以使用segue将其发送到另一个视图控制器,它将显示在标签中。我遇到问题的唯一部分实际上是将数据存储起来以便在其他地方使用。我知道使用datePicker,我可以做我想做的事情:

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
}

这将存储用户选择的日期在var selectedDate中,按下按钮时,这就是我想要的pickerView。我也知道我可以使用

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行:Int,inComponent组件)在pickerView中获取数据:Int)

唯一的问题是它每次用户更改值时都会选择数据,而不是允许我将数据存储在函数外部的变量中,以便在我的@IBAction函数buttonPressed方法中使用它。提前谢谢!

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!

推荐答案

好吧,在尝试了不同的事情后,我终于想出了解决问题的方法。它可能不是更有经验的开发人员所做的,但它对我来说就像我想要的那样。这是我做的:

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]

}

我只需要pickerView中的一个组件,因此当按下按钮时我将组件0的行号存储在一个变量中,然后我将该字符串存储在另一个变量中,使其等于数组我曾经填充过我的选择器视图。我通过传递所选变量来检索该行。

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.

这篇关于按下按钮时如何在变量中存储选择器视图中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆