如何在 UIPickerView 中获取用户选择并在其他地方使用它?
Posted
技术标签:
【中文标题】如何在 UIPickerView 中获取用户选择并在其他地方使用它?【英文标题】:how to get user selection in UIPickerView and use it else where? 【发布时间】:2016-07-29 23:29:35 【问题描述】:我要做的就是根据用户在选择器菜单中选择的内容更改 min avg 和 max 的值,以便我可以在 MinC AvgC 和 MaxC 标签计算中使用它们。例如,如果用户选择 a1,则 min = 10,avg = 15,max = 20,但如果用户选择 a2,我希望 min = 20,avg = 25,max = 30。请帮助,谢谢。感谢您的时间、精力和支持。下面是我的代码,目前正在运行,没有任何错误:
class ViewController: UIViewController, UIPickerViewDelegate, UITextFieldDelegate
@IBOutlet var PLabel: UILabel!
@IBOutlet weak var C: UITextField!
@IBOutlet var MinC: UILabel!
@IBOutlet var AvgC: UILabel!
@IBOutlet var MaxC: UILabel!
var min = 0
var avg = 0
var max = 0
var P = ["a1","a2","a3","a4"]
var CFiller = ["0"]
override func viewDidLoad()
super.viewDidLoad()
PLabel.text = P[0]
MinC.text = CFiller[0]
AvgC.text = CFiller[0]
MaxC.text = CFiller[0]
C.keyboardType = UIKeyboardType.NumberPad
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
return 1
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
return P.count
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
return P[row]
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
var PSelected = P[row]
PLabel.text = PSelected
@IBAction func CalcButton(sender: AnyObject)
if let ic = Int (C.text!)
MinC.text = "\(min * ic)"
AvgC.text = "\(avg * ic)"
MaxC.text = "\(max * ic)"
【问题讨论】:
【参考方案1】:在我看来,您只需要使用 switch 语句即可实现目标。
这可能看起来像这样:
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
var PSelected = P[row]
PLabel.text = PSelected
switch PSelected
case "a1":
min = 10
avg = 15
max = 20
case "a2":
min = 20
avg = 25
max = 30
...
default:
break
如果您愿意,也可以更有效地进行设置,如下所示:
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
var PSelected = P[row]
PLabel.text = PSelected
var increment = 10
min = 10
avg = 15
max = 20
min += increment*row //if a1, then row == 0, so nothing is added
avg += increment*row
max += increment*row
【讨论】:
非常感谢。非常感谢您的帮助。效果很好! @RayX1993 如果答案有帮助,为什么不点赞?以上是关于如何在 UIPickerView 中获取用户选择并在其他地方使用它?的主要内容,如果未能解决你的问题,请参考以下文章
点击完成时如何在uipickerview中获取当前选定的行(具有多个选择器)
使用 UIButton 从 UIPickerView 向 UILabel 显示输出