2015-05-14 3 views
0

Позвольте мне сначала объяснить концепцию. Я задаю пользователю 3 вопроса, которые хранятся в NSArray. Существует один UITextField, который пользователь будет использовать для написания всех 3 ответов на вопросы.Как переходить к новому UIViewController в конце массива count

Что бы я хотел произойти, когда все три вопроса были отображены из массива, в следующий раз, когда пользователь нажмет следующий UIButton, он перейдет к новому UIViewController. Я создал segue в main.storyboard и дал ему идентификатор 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

Вы должны проверить свой 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) 
} 

EDIT:

Вы не проверяли индекс при получении значения из вашего массива для отображения текста. Он переполняется, когда вы нажимаете кнопку NEXT на последнем вопросе.

@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) 
    } 
} 
+0

Привет, Спасибо, это сделало работу segue, но это происходит при отображении последнего вопроса, а не после того, как последний вопрос был отображен. Имеет ли это смысл? спасибо – Nick89

+0

Я пробовал это, но он просто заставляет приложение снова крушить, как раньше. Я тоже устал, добавив - 1 после .count, но segue все еще случается слишком рано. спасибо – Nick89

+0

Разрушен ли он в этой функции или где-то еще? Трудно сказать, не зная логики остальной части приложения. И ваш вопрос на самом деле не связан с инициированием сеанса. Это чисто индекс массива вне диапазона. –

Смежные вопросы