如何使用Swift中的字符串数组值填充UISegmentedControl索引

时间:2015-03-18 20:01:10

标签: arrays xcode swift uisegmentedcontrol

我有一个带有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)
    }

1 个答案:

答案 0 :(得分:0)

解决方案是:

selectedSegmentIndex = 2