iosswiftuiviewuiswipegesturerecognizer

UIView Swipe Gesture Changing images


I am trying to implement a left and right swipe gesture to change the image on my UIView.

I have done the following:

if art_title.text == "Art Collection" {
        var imageList = ["Boulder Bean","Mother of Earth","Bamboozled","Black Figures","Modest Angel"]
        var index = 0

        func leftSwipe(_ sender: UISwipeGestureRecognizer) {

            if index < imageList.count - 1 {
                index = index + 1
                art_image.image = UIImage(named: imageList[index])
            }
        }

        func rightSwipe(_ sender: UISwipeGestureRecognizer) {
            if index > 0 {
                index = index - 1
                art_image.image = UIImage(named: imageList[index])
            }
        }
    }

I am now getting a crash when i try to swipe on Any annotation.


Solution

  • In general, you will have a List of images and an Index value to track where you are in the list.

    When you "swipe right" you decrement the index by 1... when you swipe left, you increment the index by 1.

    If the index drops below 0 (the first element of your array), you either reset it to 0 and leave the image as-is, or you "wrap it around" to the end of the array. Similarly, if the index gets greater than the number of elements in the array, you can "wrap it around" to zero.

    So, for example:

    // initialize
    var imageList = ["flower", "balloon", "cat", "dog"]
    var index = 0
    
    // set the first image
    art_image.image = UIImage(named: imageList[index])
    
    // on swipe left (arrays are Zero based)
    if index < imageList.count - 1 {
        index = index + 1
        art_image.image = UIImage(named: imageList[index])
    }
    
    // on swipe right
    if index > 0 {
        index = index - 1
        art_image.image = UIImage(named: imageList[index])
    }
    

    and so on...

    That should get you on your way.