在Swift图像阵列中来回滑动

Luk*_*ivi 5 arrays ios uiswipegesturerecognizer swift

我有一系列图像,我希望能够向前(向左)滑动到下一个图像,或向后(向右)滑动到上一个图像.当imageList达到-1 /超出范围时,应用程序崩溃.我无法弄清楚如何将其保持在范围内的逻辑.

这是我的代码:

var imageList:[String] = ["image1.jpg", "image2.jpg", "image3.jpg"]
let maxImages = 2
var imageIndex: NSInteger = 1
Run Code Online (Sandbox Code Playgroud)

滑动手势在我的viewDidLoad()方法中,不确定这是否是正确的位置......:

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var swipeRight = UISwipeGestureRecognizer(target: self, action: "swiped:") // put : at the end of method name
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    self.view.addGestureRecognizer(swipeRight)

    var swipeLeft = UISwipeGestureRecognizer(target: self, action: "swiped:") // put : at the end of method name
    swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
    self.view.addGestureRecognizer(swipeLeft)

    image.image = UIImage(named:"image1.jpg")

}


func swiped(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {

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

        /*No clue how to make it go back to the previous image and 
        when it hits the last image in the array, it goes back to 
        the first image.. */

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


            if imageIndex > maxImages {

                imageIndex = 0

            }

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

            imageIndex++



        default:
            break //stops the code/codes nothing.


        }

    }


}
Run Code Online (Sandbox Code Playgroud)

非常感谢提前!

Zel*_* B. 12

首先,您的图像索引应设置为零,因为数组元素从零开始,但这不是您的问题的根源

var imageIndex: NSInteger = 0
Run Code Online (Sandbox Code Playgroud)

然后你的刷卡功能应该如下

func swiped(gesture: UIGestureRecognizer) {

if let swipeGesture = gesture as? UISwipeGestureRecognizer {

    switch swipeGesture.direction {

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

        // decrease index first

        imageIndex--

        // check if index is in range

        if imageIndex < 0 {

            imageIndex = maxImages

        }

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

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

        // increase index first

        imageIndex++

        // check if index is in range

        if imageIndex > maxImages {

            imageIndex = 0

        }

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




    default:
        break //stops the code/codes nothing.


    }

}


}
Run Code Online (Sandbox Code Playgroud)

  • 你好,这是有效的,但我怎么能添加拖动动画. (3认同)