我的视图控制器中有一个选择器视图,并希望将所选行中的数据保存在变量中。我不想要一个按钮。我的Picker View附加到视图控制器委托和数据源。这是我的选择器视图代码:
var colors = ["ISERV 1","ISERV 2","ISERV 3"]
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return colors.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return colors[row]
}
答案 0 :(得分:2)
您需要实施didSelectRow:
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
let variable = colors[row]
}
答案 1 :(得分:0)
这个代码你可以试试
var numbers = [1, 2 , 3]
var num:Int! = 1
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return numbers.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return numbers[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
num = numbers[row]
}
@IBAction func saveAccounts(_ sender: UIButton)
{
if num == 1 {
let aleart = UIAlertController(title: "The number is ONE", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "ok", style: .default) { (action) in
}
aleart.addAction(action)
present(aleart, animated: true, completion: nil)
}else if num == 2 {
let aleart = UIAlertController(title:"The number is TOW", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "ok", style: .default) { (action) in
}
aleart.addAction(action)
present(aleart, animated: true, completion: nil)
}else if num == 3 {
let aleart = UIAlertController(title: "The number is THREE", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "ok", style: .default) { (action) in
}
aleart.addAction(action)
present(aleart, animated: true, completion: nil)
}