Cocoa Touch - UISegmentedControl title is not working in IF/ELSE statement
I'm trying to write a basic DST converter. I have a segmented control with 3 choices, their titles (surprisingly) are Distance, Speed and Time. I have 2 input text fields and a calcul开发者_Python百科ate button, as well as 2 labels for each text field with the type of measurement required and it's units. Making a selection on the segmented control should update the view accordingly. The variables have all been declared as IBOutlets, @property, @synthesize, and the code sits in an IBAction method, which is connected to the segmented control. The following code does not work, am I missing something completely obvious? (NSLog shows the correct title)
NSString *choice;
choice = [dstChoiceSegmentedControl titleForSegmentAtIndex: dstChoiceSegmentedControl.selectedSegmentIndex];
NSLog(@"Choice |%@|", choice);
if (choice == @"Distance") {
firstLabel.text = @"Speed:";
firstUnitsLabel.text = @"kts";
secondLabel.text = @"Time:";
secondUnitsLabel.text = @"hrs";
answerUnitsLabel.text = @"nm";
} else if (choice == @"Speed") {
firstLabel.text = @"Distance:";
firstUnitsLabel.text = @"nm";
secondLabel.text = @"Time:";
secondUnitsLabel.text = @"hrs";
answerUnitsLabel.text = @"kts";
} else if (choice == @"Time") {
firstLabel.text = @"Distance:";
firstUnitsLabel.text = @"nm";
secondLabel.text = @"Speed:";
secondUnitsLabel.text = @"kts";
answerUnitsLabel.text = @"hrs";
}
Thanks for your help (and I hope it's not some silly error that is staring me right in the face)!
You cannot compare strings this way. You need to do:
[choice isEqualToString:@"Distance"];
But if I were you, I'd check for the indicies instead.
edit: To explain it further: what you're doing with choice == @"Distance"
is comparing a pointer with a string, which will not work. You need to call the string objects comparing method as shown above.
精彩评论