从UIpickerview中提取值作为变量

时间:2017-04-05 15:36:16

标签: ios swift xcode8 uipickerview

所以我有一个UIpickerview的代码,我希望将值选为后面使用的变量,我尝试使用变量引力,但它说"变量引力的初始化从未使用.... "这是我的代码:

 var g = ["9.807", "3.711"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

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

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    var gravity = Float(g[row])
}

3 个答案:

答案 0 :(得分:0)

您的gravity var是本地,因此给定的警告完全有意义(即,其范围限制到给定函数)。

您应该使用以下UIPickerView方法获取当前选定的索引:

func selectedRow(inComponent component: Int) -> Int

例如:

let gIndex = pickerView.selectedRow(inComponent: 0)
let gValue = Float(g[gIndex])!

请注意,您甚至需要实现didSelectRow委托方法来获取此信息。

正如评论中正确指出的那样,您当然需要声明并将UIPickerView绑定到视图控制器的实例var:

@IBOutlet weak var pickerView: UIPickerView!

答案 1 :(得分:0)

您需要将var声明在方法范围之外:

var gravity: Float?
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
   gravity = Float(g[row])
}

局部变量范围仅限于该方法,因为您不会在该方法中使用它,您会收到警告。

这是Swift而不是Javascript:)

答案 2 :(得分:0)

要使用pickerView,请先提及其DataSource和Delegate。

UIPickerViewDataSource, UIPickerViewDelegate

现在通过右键单击pickerView来创建它 - >到ViewContoller.swfit.You会得到:

@IBOutlet var pickerView: [UIPickerView]!

创建一个数组,其中包含您要在pickerView中显示的内容。就像这样:

var array:[String] = ["David","Mikel","Akhil","Akshay","Zlatan"]

现在你必须使用pickerView函数。只有在类中提到DataSource和Delegate时,才能使用这些函数。功能是:

// number of rows or number of components
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

// number of rows that we have to set
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return array.count
}

// set title in picker view according to the elements
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return array[row]
}

// when an element is selected, store in a string
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    pickerString = array[row]
    print(pickerString) // pickerString is String type. You can create this, to show the content selected.
}