我有一组图像,我希望能够向前(向左)滑动到下一个图像,或向后(向右)滑动到上一个图像。当 imageList 达到 -1/超出范围时,应用程序崩溃。我无法弄清楚如何将其保持在范围内的逻辑。
这是我的代码:
var imageList:[String] = ["image1.jpg", "image2.jpg", "image3.jpg"]
let maxImages = 2
var imageIndex: NSInteger = 1
滑动手势位于我的 viewDidLoad() 方法中,不确定这是否是正确的位置...:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var swipeRight = UISwipeGestureRecognizer(target: self, action: "swiped:") // put : at the end of method name
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "swiped:") // put : at the end of method name
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
self.view.addGestureRecognizer(swipeLeft)
image.image = UIImage(named:"image1.jpg")
}
func swiped(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right :
println("User swiped right")
/*No clue how to make it go back to the previous image and
when it hits the last image in the array, it goes back to
the first image.. */
case UISwipeGestureRecognizerDirection.Left:
println("User swiped Left")
if imageIndex > maxImages {
imageIndex = 0
}
image.image = UIImage(named: imageList[imageIndex])
imageIndex++
default:
break //stops the code/codes nothing.
}
}
}
预先非常感谢!
首先,您的图像索引应设置为零,因为数组元素从零开始,但这不是问题的根源
var imageIndex: NSInteger = 0
那么你的滑动功能应该如下所示
func swiped(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right :
println("User swiped right")
// decrease index first
imageIndex--
// check if index is in range
if imageIndex < 0 {
imageIndex = maxImages
}
image.image = UIImage(named: imageList[imageIndex])
case UISwipeGestureRecognizerDirection.Left:
println("User swiped Left")
// increase index first
imageIndex++
// check if index is in range
if imageIndex > maxImages {
imageIndex = 0
}
image.image = UIImage(named: imageList[imageIndex])
default:
break //stops the code/codes nothing.
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)