【问题标题】:How to fill UISegmentedControl Indexes with String Array Values in Swift如何在 Swift 中用字符串数组值填充 UISegmentedControl 索引
【发布时间】:2015-05-21 19:12:17
【问题描述】:

我有一个带有 4 个索引的 UISegmentedControl,其中包含从字符串数组收集的测验答案。我的目标是用错误答案填充所有 4 个索引,然后用正确答案随机替换其中一个索引。当我运行模拟器时,应用程序似乎进入了一个无限循环,并且视图永远不会加载。当我注释掉整个第二个 for 循环(应该用不正确的猜测填充索引)时,视图加载并且分段控件出现,其中一个段中只显示了正确的答案。为什么会进入无限循环(如果是这种情况),如何修改此代码以根据需要显示分段控件?

    func nextQuestion()
    {
        questionNumberLabel.text = String(format: "Question %1$d of %2$d",
            (correctGuesses + 1), numberOfQuestions)
        answerLabel.text = ""
        correctAnswer = allAnimals.removeAtIndex(0)
        animalImageView.image = UIImage(named: correctAnswer) // next animal

        // re-enable UISegmentedControls and delete prior segments
        for segmentedControl in segmentedControls
        {
            segmentedControl.enabled = true
            segmentedControl.removeAllSegments()
        }

        // place guesses on displayed UISegmentedControls
        allAnimals.shuffle() // shuffle array
        var i = 0        
        for segmentedControl in segmentedControls
        {
            if !segmentedControl.hidden
            {
                var segmentIndex = 0

                while segmentIndex < 4
                {
                    if i < allAnimals.count && correctAnswer != allAnimals[i]
                    {
                        segmentedControl.insertSegmentWithTitle(
                            getStringFromFile(allAnimals[i]),
                            atIndex: segmentIndex, animated: false)
                        ++segmentIndex
                    }
                    ++i
                }
            }
        }

        // pick random segment and replace with correct answer        
        let randomIndexInRow = Int(arc4random_uniform(UInt32(4)))
        segmentedControls[0].removeSegmentAtIndex(
            randomIndexInRow, animated: false)
        segmentedControls[0].insertSegmentWithTitle(
            getStringFromFile(correctAnswer),
            atIndex: randomIndexInRow, animated: false)
    }

【问题讨论】:

    标签: arrays xcode swift uisegmentedcontrol


    【解决方案1】:

    解决办法是:

    selectedSegmentIndex = 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多