2016-08-06 2 views
0

С вашей последней помощью мой цикл работает хорошо. Но только один раз. Если я пытаюсь загрузить его я получаю следующую ошибку: «Индекс вне диапазона» в следующей строке:Позиционирование воинских взглядов программно в быстром

let cardOnTop = cards[index-8] 

Может кто-нибудь мне помочь?

Вот мой код:

func layoutCards() { 

     // create cards array with several elements 
     var cards = (1...64).map { _ in UIView() }// array with several cards 


     //Loop through each card in the array 
     for index in 0...cards.count-1 { 



      // place the card in the view and turn off translateAutoresizingMask 
      let thisCard = cards[index] 

      thisCard.layer.borderWidth = 1 
      thisCard.layer.borderColor = UIColor.blackColor().CGColor 
      thisCard.backgroundColor = UIColor.greenColor() 

      thisCard.translatesAutoresizingMaskIntoConstraints = false 
      midView.addSubview(thisCard) 

      //set the height and width constraints 
      let widthConstraint = NSLayoutConstraint(item: thisCard, attribute: .Width, relatedBy: .Equal, toItem: midView, attribute: .Width, multiplier: 0.125, constant: 0) 
      let heightConstraint = NSLayoutConstraint(item: thisCard, attribute: .Height, relatedBy: .Equal, toItem: midView, attribute: .Height, multiplier: 0.125, constant: 0) 
      midView.addConstraints([heightConstraint, widthConstraint]) 

      //set the horizontal position 

      if (columnCounter > 0) { 

       // card is not in the first column 
       let cardOnTheLeft = cards[index-1] 

       let leftSideConstraint = NSLayoutConstraint(item: thisCard, attribute: .Left, relatedBy: .Equal, toItem: cardOnTheLeft, attribute: .Right, multiplier: 1, constant: 0) 

       //add constraint to the contentView 
       midView.addConstraint(leftSideConstraint) 

      } else { 

       //card is in the first column 

       let leftSideConstraint = NSLayoutConstraint(item: thisCard, attribute: .Left, relatedBy: .Equal, toItem: midView, attribute: .Left, multiplier: 1, constant: 0) 

       //add constraint to the contentView 
       midView.addConstraint(leftSideConstraint) 

      } 


      //set the vertical position 

      if (rowCounter > 0) { 

       // card is not in the first row 
       let cardOnTop = cards[index-8] 

       let topConstraint = NSLayoutConstraint(item: thisCard, attribute: .Top, relatedBy: .Equal, toItem: cardOnTop, attribute: .Bottom, multiplier: 1, constant: 0) 

       // add constraint to the contentView 
       midView.addConstraint(topConstraint) 

      } else { 

       //card is in the first row 

       let topConstraint = NSLayoutConstraint(item: thisCard, attribute: .Top, relatedBy: .Equal, toItem: midView, attribute: .Top, multiplier: 1, constant: 0) 

       //add constraint to the contentView 
       midView.addConstraint(topConstraint) 

      } 



      //increment the column counter 
      columnCounter = columnCounter+1 

      //if the column counter reaches the fifth column reset it and increase the row counter 
      if (columnCounter >= 8) { 
       columnCounter = 0 
       rowCounter = rowCounter+1 
      } 




     } // end of the loop 



    } 
+0

Для любого значения индекса менее 8, что линия пытается получить доступ к индексу меньше 0. Первый вызов будет смотреть на карты [ -8], что явно выходит за допустимые пределы. Вам нужно изменить свой код, чтобы защитить его. – Westside

+0

if (rowCounter> 0 && index> 7) {... – Idan

ответ

0

Вы говорите, что это происходит сбой при запуске его во второй раз. Это потому, что у вас, видимо, есть rowCounter и columnCounter, объявленные как свойства, и вы не устанавливаете rowCounter и columnCounter обратно в 0 каждый раз, когда вызывается layoutCards().

Сделать rowCounter и columnCounter локальные переменные layoutCards():

func layoutCards() { 
    var rowCounter = 0 
    var columnCounter = 0 

    // create cards array with several elements 
    var cards = (1...64).map { _ in UIView() }// array with several cards 
+0

Еще раз спасибо! Теперь это работает. Такая глупая ошибка, я был действительно слепым ... – Roman

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