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

时间:2017-05-18 02:49:08

标签: swift3 uiswipegesturerecognizer

我是初学者Swift 3 - UISwipe手势,但如果使用数组则无法正常工作。

这是我的代码。

我如何进行编码,以便标签仅从" hello1" to" hello2"然后再向左滑动到" hello3"。也可以从" hello3"向右滑动到右后卫。 to" 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 {

    }
}

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

您也可以使用以下代码

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

    }