我希望创建一个侧面滑动照片库。有许多教程展示如何使用tableview创建一个,但我想创建一个以图像开头的图库,并允许您向左或向右滑动以进行浏览。有没有人知道github扩展或教程,或有任何知识帮助指出我正确的方向?谢谢。
答案 0 :(得分:10)
您可以在常规viewController上执行此操作...您可能会为此找到一些动画,但我想这是朝着正确方向迈出的一步:
首先,定义一个imageView和里面的图像:
// Connect a UIImageView to the outlet below
@IBOutlet weak var swipeImageView: UIImageView!
// Type in the names of your images below
let imageNames = ["","","","",""]
然后,在viewDidLoad中,为方向设置gestureRecognizers:
var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
self.view.addGestureRecognizer(swipeLeft)
之后,您可以设置调用以管理图像开关的功能。
var currentImage = 0
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Left:
if currentImage == imageNames.count - 1 {
currentImage = 0
}else{
currentImage += 1
}
swipeImageView.image = UIImage(named: imageNames[currentImage])
case UISwipeGestureRecognizerDirection.Right:
if currentImage == 0 {
currentImage = imageNames.count - 1
}else{
currentImage -= 1
}
swipeImageView.image = UIImage(named: imageNames[currentImage])
default:
break
}
}
}
全视图控制器代码:
import UIKit
class ViewController: UIViewController {
// Connect a UIImageView to the outlet below
@IBOutlet weak var swipeImageView: UIImageView!
// Type in the names of your images below
let imageNames = ["","","","",""]
var currentImage = 0
override func viewDidLoad() {
super.viewDidLoad()
var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
self.view.addGestureRecognizer(swipeLeft)
// Do any additional setup after loading the view, typically from a nib.
}
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Left:
if currentImage == imageNames.count - 1 {
currentImage = 0
}else{
currentImage += 1
}
swipeImageView.image = UIImage(named: imageNames[currentImage])
case UISwipeGestureRecognizerDirection.Right:
if currentImage == 0 {
currentImage = imageNames.count - 1
}else{
currentImage -= 1
}
swipeImageView.image = UIImage(named: imageNames[currentImage])
default:
break
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}