如何快速确定在发送方函数之外选择了哪个分段控件

1 uisegmentedcontrol swift

请原谅对 swift-ness 的新手。我正在创建一个 BMI 计算器应用程序。该应用程序允许用户使用分段控件选择英制或公制。基于分段控件,我更改了占位符文本。在“计算”按钮上,我调用一个分机来进行计算。我的问题是:在按下按钮的这个动作中,我如何确定选择了哪个段,以便我可以调整计算?这是我当前的代码:

@IBAction func segmentChanged(sender: UISegmentedControl) {
    if sender.selectedSegmentIndex == 0 {
        textInputHeight.placeholder = "Enter height in inches"
        textInputWeight.placeholder = "Enter weight in pounds"
    }
    else {
        textInputHeight.placeholder = "Enter height in centimeters"
        textInputWeight.placeholder = "Enter weight in kilograms"
    }
}

@IBAction func CalulateBMIButton() {
    if let height = textInputHeight.text.toDouble() {
        if let weight = textInputWeight.text.toDouble() {
            let bmiCalc = BMICalculator(height: height, weight: weight)
            labelOutputBMI.text = "BMI is: \(round(10.0 * bmiCalc.bmi) / 10)"
            labelOutputBMI.hidden = false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

aah*_*ens 5

你需要一个 UISegmentedControl 的出口

@IBOutlet weak var segmentedControl: UISegmentedControl!
Run Code Online (Sandbox Code Playgroud)

然后您可以使用访问当前选择。

segmentedControl.selectedSegmentIndex
Run Code Online (Sandbox Code Playgroud)