2016-04-01 13 views
0

私はここに新しいと私はまた、スウィフトの初心者です!スワイプUIImageView配列ループ

UIImageViewを左右にスワイプして作成しようとしていますが、最後の画像にアプリケーションクラッシュが発生したとき、最初の画像にあって右にスワイプしようとすると同じクラッシュが発生します。 私のやりたいことは、画像の配列が最後の画像に到達したときにループの最初の画像に戻ってきます。だれでも助けてくれますか? ありがとうございます! ここに私のコードです。

funcは(ジェスチャー:UIGestureRecognizer)スワイプ{ CATransaction.begin()

 CATransaction.setAnimationDuration(animationDuration) 
     CATransaction.setCompletionBlock { 
      let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.switchingInterval * NSTimeInterval(NSEC_PER_SEC))) 
      dispatch_after(delay, dispatch_get_main_queue()) { 
      } 


     } 

     let transition = CATransition() 
     transition.type = kCATransitionFade 
     chracters.layer.addAnimation(transition, forKey: kCATransition) 

     CATransaction.commit() 


     if let swipeGesture = gesture as? UISwipeGestureRecognizer { 

      switch swipeGesture.direction { 

      case UISwipeGestureRecognizerDirection.Right : 
       print("User swiped right") 

       // decrease index 

       imageIndex -= 1 


       // check if index is in range 

       if swipePosition > imageList.count-1{ 

       // Do Nothing 
       } else { 

        swipePosition += 1 
       } 
       chracters.image = UIImage(named: imageList[imageIndex]) 

      case UISwipeGestureRecognizerDirection.Left: 
       print("User swiped Left") 

       // increase index first 

       imageIndex += 1 

       // check if index is in range 

       if swipePosition == 0 { 

        //Do Nothing 
       } else { 

        swipePosition -= 1 
       } 

       chracters.image = UIImage(named: imageList[imageIndex]) 



      default: 
       break; 
       //stops the code 



      } 

     } 


    } 

答えて

1

まず、あなたの条件はamiguousのようです、あなたの代わりにパラメータ:imageIndexのswipePosition自体を使用することができます。第二に、あなたのchracters.imageはif/elseブロック内にあるべきです。以下は更新されたスニペットです。 imageIndexを使用する場合は、それに応じてimageIndexを変更することができます。また、最後の画像から最初の画像、そして最初の画像から最後の画像に切り替えるためのコードが追加されました。

if swipePosition > imageList.count-1{ 
    swipePosition = 0 
    chracters.image = UIImage(named:imageList[swipePosition] 
} else { 
    chracters.image = UIImage(named:imageList[swipePosition] 
    swipePosition += 1 
} 

case UISwipeGestureRecognizerDirection.Left: 
print("User swiped Left") 
// check if index is in range 
if swipePosition == 0 { 
    swipePosition = imageList.count-1 
    chracters.image = UIImage(named:imageList[swipePosition] 
} else { 
    chracters.image = UIImage(named:imageList[swipePosition] 
    swipePosition -= 1 
} 
+0

ありがとうございました。 – Matt

+0

喜んで助けてください。それがうまくいけば、同じ問題に直面している他の人たちがこれから恩恵を受けることができるように、これを正解とマークできます。 –