分段控件不变索引

时间:2018-08-29 22:41:24

标签: ios swift uisegmentedcontrol

我正在编写游戏,并且具有用于用户选择难度等级的分段控件。我在案例中添加了一些简单的代码来检查索引是否更改,但似乎没有更改。这是代码:

@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 difficulty selected.")
    }
}

现在,当我在模拟器中对此进行测试时,打印到控制台的唯一内容是“选择了平均难度”。无论我选择哪一个。为什么会发生这种情况,我该如何解决?

编辑:通过在另一个论坛上提问,我找到了一个可行的答案。谢谢您的帮助。以下是对我有用的答案:Here is the link to the answer

2 个答案:

答案 0 :(得分:2)

这部分代码将onePlayerGameType设置为.average,当您再次选择控件时,该值仍为.average

 case .average:
        onePlayerGameType = typeOfGame.average
  

我有一个分段控件供用户选择难度级别

如果仅此而已,为什么需要switch而不仅仅是直接分配?

enum typeOfGame : Int {
     case sluggish
     case average
     case ninja
}

@IBAction func chooseOnePlayerDifficulty(_ sender: UISegmentedControl) {
                           // assuming  typeOfGame is enum
    let difficultyLevel =  typeOfGame(rawValue: sender.selectedSegmentIndex)
    onePlayerGameType = difficultyLEvel
}

答案 1 :(得分:0)

我希望您在StoryBoard / XIB或代码中向段控制注册了操作方法

segmentedControl.addTarget(self, action: "chooseOnePlayerDifficulty:", forControlEvents: .ValueChanged)

尝试以下操作

@IBAction func chooseOnePlayerDifficulty(_ sender: UISegmentedControl) {
    let selectedSegment = sender.selectedSegmentIndex
    switch selectedSegment {
    case 0:
        onePlayerGameType = typeOfGame.sluggish
        print("Sluggish difficulty selected.")
    case 1:
        onePlayerGameType = typeOfGame.average
        print("Average difficulty selected.")
    case 2:
        onePlayerGameType = typeOfGame.ninja
        print("Ninja difficulty selected.")
    default:
        print("Assing default")
    }
}

编辑:右键@JakeG,更新了答案