So I'm making a game, and I have a segmented control for the user to select a difficulty level. Inside the cases for the control, I wrote some simple code to see if the difficulty changes when the user selects a different segment. Here it is:
@IBAction func chooseOnePlayerDifficulty(_ sender: UISegmentedControl) {
switch onePlayerGameType {
case .sluggish:
onePlayerGameType = typeOfGame.sluggish
print("Sluggish difficulty selected")
case .average:
onePlayerGameType = typeOfGame.average
print("Average difficulty selected")
case .ninja:
onePlayerGameType = typeOfGame.ninja
print("Ninja game mode selected")
}
}
When I test it and select different segments, the only thing that shows up in the console is "Average difficulty selected."
Is the problem that the UISegmentedControl is not reflecting taps on different segments or that onePlayerGameType isn’t updated when the user taps a different segment? If the former, the problem might be isEnabled or isUserInteractionEnabled being set to false, either in code or in Interface Builder. If the latter, the problem is that you are not using selectedSegmentIndex. See the following for an example of how to do so: Conjugar/BrowseInfoVC.swift at master · vermont42/Conjugar · GitHub
You probably want to update the value of onePlayerGameType before (and not in) the switch based on the value of the selectedSegmentIndex. Something like this:
@IBAction func chooseOnePlayerDifficulty(_ sender: UISegmentedControl) {
guard let selectedGameType = typeOfGame(rawValue: sender.selectedSegmentIndex) else {
fatalError("no corresponding game type for the index selected by the segmented control")
}
onePlayerGameType = selectedGameType
switch onePlayerGameType {
case .sluggish:
print("Sluggish difficulty selected")
case .average:
print("Average difficulty selected")
case .ninja:
print("Ninja game mode selected")
}
}
For this to work, the typeOfGame enum would have to be declared to have an Int raw value and the cases would need to be in the same order as your segmented control:
enum typeOfGame: Int {
case sluggish, average, ninja
}