我初学者学习Swift 3
- UIS滑动手势,但如果使用数组则无法工作。
这是我的代码。
如何编码,使标签仅从"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]
}
}
}