Swift3 Swift 3-使用数组向左滑动以更改标签
我是初学者,正在学习Swift 3,但如果使用数组,则无法使用 这是我的密码 如何编码,使标签仅从“hello1”更改为“hello2”,然后再次向左滑动至“hello3”。同时从“hello3”到“hello2”和“hello1”反向向右回扫。或者循环回到第一个 谢谢Swift3 Swift 3-使用数组向左滑动以更改标签,swift3,uiswipegesturerecognizer,Swift3,Uiswipegesturerecognizer,我是初学者,正在学习Swift 3,但如果使用数组,则无法使用 这是我的密码 如何编码,使标签仅从“hello1”更改为“hello2”,然后再次向左滑动至“hello3”。同时从“hello3”到“hello2”和“hello1”反向向右回扫。或者循环回到第一个 谢谢 class ChangeLabelViewController: UIViewController { var helloArray = ["Hello1", "Hello2", "Hello3"] var currentAr
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]
}
}
}
func handlesweeps(发送方:UISweepGestureRecognitor){
如果sender.direction==.left{
如果(currentArrayIndex0)
{
currentArrayIndex-=1
如果currentArrayIndex==-1
{
currentArrayIndex=0
让indexPath=indexPath(项:currentArrayIndex,节:0)
helloLabel.text=helloArray[indexPath.row]
}
否则{
让indexPath=indexPath(项:currentArrayIndex,节:0)
helloLabel.text=helloArray[indexPath.row]
}
}
}
谢谢Simonly。这是我学到的很棒的技巧和教程。我会进一步消化代码。希望这能帮助你!:)@JimmyWongI按照代码进行操作,当运行到最后一个数组时,应用程序崩溃,因为“索引超出范围”谢谢你的指导。哦…现在你可以检查了。谢谢Jigar。代码工作得很好。我会尽力理解的。这是我的荣幸,Jimmy