如何在UIPickerView中选择用户并在其他地方使用它?

时间:2016-07-29 23:29:36

标签: arrays swift uipickerview

我想要做的就是根据用户在选择器菜单中选择的内容更改最小平均值和最大值,以便我可以在MinC AvgC和MaxC标签计算中使用它们。例如,如果用户选择a1然后min = 10,avg = 15,max = 20,但是如果用户选择a2我想要min to = 20,avg = 25,max = 30.请帮助并谢谢。您的时间,精力和支持表示赞赏。 bellow是我的代码,目前正在运行,没有任何错误:

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 个答案:

答案 0 :(得分: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

}