如何将UIPickerView
选择存储到变量中?
func pickerView(pickerView: AKPickerView, didSelectItem item: Int) {
}
let selected = pickerView(samplePickerView, what goes here?)
答案 0 :(得分:1)
首先,我猜你会拿着一个数组。因此,让我们将其命名为pickerarray,并将其作为字符串数组。
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
selected = pickerarray[row] // selected is the variable
}
这里使用的是pickerview的row属性。
修改强> 为了您的澄清,我输入了整个代码
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource,UIPickerViewDelegate {
@IBOutlet var MyPickerView: UIPickerView!
var selected = ""
let words: NSArray = ["Cat", "Chicken", "fish", "Dog",
"Mouse", "Guinea Pig", "monkey"]
override func viewDidLoad() {
super.viewDidLoad()
MyPickerView.delegate = self
MyPickerView.dataSource = self
selected = words[0] // setting the default value
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return words.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return "\(words[row])"
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selected = words[row] as! String
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
要从任何函数的pickerview访问所选值,请使用
let selectedvalue = selected