首先让我解释一下这个概念。我问用户3个问题,这些问题存储在NSArray
中。用户将使用一个UITextField
来写出问题的所有3个答案。
我希望发生这种情况,当数组中显示所有三个问题时,下次用户按下下一个UIButton
时,它会转移到新的UIViewController
。我在main.storyboard中创建了segue,并为其指定了countdownSegue的标识符。
当我运行我的应用程序时,我到达最后一个问题并按下“下一步”按钮,应用程序崩溃并且错误是"致命错误:数组索引超出范围" - 我不明白为什么。我的代码在下面显示我的问题数组和按下时我的按钮发生了什么。任何帮助非常感谢。
let questions = ["Where are you going?", "Which city?", "When do you go?"]
var currentQuestionIndex = 0
let placeholder = ["Country", "City", "Date"]
var currentPlaceholderIndex = 0
@IBAction func nextButton(sender: AnyObject) {
// Initial setup on button press
questionTextField.hidden = false
barImage.hidden = false
questionTextField.placeholder = placeholder[currentPlaceholderIndex]
questionLabel.text = questions[currentQuestionIndex]
questionTextField.resignFirstResponder()
// Reset text field to have no text
questionTextField.text = ""
// Displays the questions in array and displays the placeholder text in the textfield
if currentQuestionIndex < questions.count && currentPlaceholderIndex < placeholder.count {
currentQuestionIndex++
currentPlaceholderIndex++
buttonLabel.setTitle("Next", forState: UIControlState.Normal)
} else if currentQuestionIndex > questions.count && currentPlaceholderIndex > placeholder.count {
performSegueWithIdentifier("countdownSegue", sender: self)
}
}
谢谢!
答案 0 :(得分:0)
您应该针对index
检查count - 1
,因为索引是从零开始的。
if currentQuestionIndex < questions.count - 1 && currentPlaceholderIndex < placeholder.count - 1{
currentQuestionIndex++
currentPlaceholderIndex++
buttonLabel.setTitle("Next", forState: UIControlState.Normal)
} else {
performSegueWithIdentifier("countdownSegue", sender: self)
}
修改强>
从阵列中获取值以显示文本时,您没有检查索引。当您点击上一个问题的“下一步”按钮时,它会溢出。
@IBAction func nextButton(sender: AnyObject) {
// Initial setup on button press
questionTextField.hidden = false
barImage.hidden = false
questionTextField.resignFirstResponder()
// Reset text field to have no text
questionTextField.text = ""
// Displays the questions in array and displays the placeholder text in the textfield
if currentQuestionIndex < questions.count && currentPlaceholderIndex < placeholder.count {
questionTextField.placeholder = placeholder[currentPlaceholderIndex]
questionLabel.text = questions[currentQuestionIndex]
currentQuestionIndex++
currentPlaceholderIndex++
buttonLabel.setTitle("Next", forState: UIControlState.Normal)
} else {
performSegueWithIdentifier("countdownSegue", sender: self)
}
}