I am adding a segmented control that can switch from female(0) to male(1). It is for a nutrition app, so it has a range for healthy amounts of sugar, which are different between males and females. It does a calculation that results in a value of 1, 2, or 3 (sugar value) there is a text field where the amount of sugar consumed is entered and a label that shows 1, 2, or 3. It works for female, but the sugar value for male is always the same as female. I don’t know if the problem is with changing the segmented control, or with the if statements. I’m very new to this, so please be patient.
@IBOutlet weak var controller: UISegmentedControl!
@IBOutlet weak var sugarField: UITextField!
@IBOutlet weak var label: UILabel!
var calorieRatio = 1.0
var sugarValue = 1.0
var sugarValueM = 5.0
@IBAction func changeLb(_ sender: Any)
{
let sugarFieldConv :Double = Double(sugarField.text!)!
if controller.selectedSegmentIndex == 0 {
if sugarFieldConv >= 16.8 * calorieRatio { sugarValue = 1.0
}
if sugarFieldConv <= 8.3 * calorieRatio { sugarValue = 3.0
}
if sugarFieldConv > 8.3 * calorieRatio && sugarFieldConv < 16.8 * calorieRatio { sugarValue = 2.0
}
else if controller.selectedSegmentIndex == 1 {
if sugarFieldConv >= 25 * calorieRatio { sugarValueM = 1.0
}
if sugarFieldConv <= 12.5 * calorieRatio { sugarValueM = 3.0
}
if sugarFieldConv > 12.5 * calorieRatio && sugarFieldConv < 25 * calorieRatio { sugarValueM = 2.0
}
}
if controller.selectedSegmentIndex == 0 { label.text = "( sugarValue )" }
if controller.selectedSegmentIndex == 1 { label.text = "( sugarValueM )" }
}
}
}
2
Answers
Looks like you forgot to include a curly bracket right before
else if controller.selectedSegmentIndex == 1
. And then your second but last curly bracket is not needed.It appears that your code will always give one value as it’s a let and no action taken or updated, it’s not like a tableView, in tableView you can use tableView.reloadData() to update the values but here there is nothing to able to update with.
You can use it with buttons like the image: "Check the second solution using segmented"
by the code below:
Or you can use segmented but without using its action you will need a button instead but you still have and use your segmented like the image:
Code: