Search code examples
swift3uiswipegesturerecognizer

Swift 3 - Swipe left to change label by using Array


I beginner learning Swift 3 - UISwipe gesture but cannot work if using Array.

This my code.

How can I code so the Label only change from "hello1" to "hello2" then swipe left again to "hello3". Also reverse swipe to right back from "hello3" to "hello2" and "hello1". or loop back to first one.

Thanks.

class ChangeLabelViewController: UIViewController {

var helloArray = ["Hello1", "Hello2", "Hello3"]
var currentArrayIndex = 0


@IBOutlet weak var helloLabel: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(ChangeLabelViewController.handleSwipes(sender:)))

    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(ChangeLabelViewController.handleSwipes(sender:)))

    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)

    helloLabel.text = helloArray[currentArrayIndex]
}

func handleSwipes(sender: UISwipeGestureRecognizer) {

    if sender.direction == .left {
        helloLabel.text = helloArray[currentArrayIndex + 1]


    }

    if sender.direction == .right {

    }
}

Solution

  • Try this:

    if sender.direction == .left {
        currentArrayIndex = (currentArrayIndex + 1) % 3
        helloLabel.text = helloArray[currentArrayIndex]
    }
    
    if sender.direction == .right {
        currentArrayIndex = (currentArrayIndex + 3 - 1) % 3 //if uInt
        helloLabel.text = helloArray[currentArrayIndex]
    }