Swift 3 - 向左滑动以使用数组更改标签

Swift 3 - Swipe left to change label by using Array

我是初学者 Swift 3 - UISwipe 手势但如果使用 Array 则无法工作。

这是我的代码。

如何编写代码,使标签仅从 "hello1" 变为 "hello2",然后再次向左滑动至 "hello3"。同时向右反向滑动,从 "hello3" 到 "hello2" 和 "hello1"。或循环回到第一个。

谢谢。

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 {

    }
}

试试这个:

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]
}

你也可以用下面的代码来做,

func handleSwipes(sender: UISwipeGestureRecognizer) {

    if sender.direction == .left {

        if(currentArrayIndex < helloArray.count - 1)
        {
            currentArrayIndex += 1
            let indexPath = IndexPath(item: currentArrayIndex, section: 0)
            helloLabel.text = helloArray[indexPath.row]
        }
    }

    if sender.direction == .right {

        if(currentArrayIndex > 0)
        {
            currentArrayIndex -= 1
            if currentArrayIndex == -1
            {
                currentArrayIndex = 0
                let indexPath = IndexPath(item: currentArrayIndex, section: 0)
                helloLabel.text = helloArray[indexPath.row]
            }
            else {
                let indexPath = IndexPath(item: currentArrayIndex, section: 0)
                helloLabel.text = helloArray[indexPath.row]
            }
        }

    }