如何识别四个方向的滑动

我需要用滑动来识别滑动手势向下然后向右。但是在快速 UISwipeGesture認識器有预先确定的正确方向。.我不知道如何使用其他方向。.

136380 次浏览

每个方向都需要一个 UISwipeGestureRecognizer。这有点奇怪,因为 UISwipeGestureRecognizer.direction属性是一个选项样式的位掩码,但是每个识别器只能处理一个方向。如果愿意,可以将它们全部发送到同一个处理程序,然后在那里进行排序,或者将它们发送到不同的处理程序。这里有一个实现方法:

override func viewDidLoad() {
super.viewDidLoad()


let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeRight.direction = .right
self.view.addGestureRecognizer(swipeRight)


let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeDown.direction = .down
self.view.addGestureRecognizer(swipeDown)
}


@objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {


if let swipeGesture = gesture as? UISwipeGestureRecognizer {


switch swipeGesture.direction {
case .right:
print("Swiped right")
case .down:
print("Swiped down")
case .left:
print("Swiped left")
case .up:
print("Swiped up")
default:
break
}
}
}

斯威夫特3:

override func viewDidLoad() {
super.viewDidLoad()


let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)


let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeDown)
}


func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
print("Swiped right")
case UISwipeGestureRecognizerDirection.down:
print("Swiped down")
case UISwipeGestureRecognizerDirection.left:
print("Swiped left")
case UISwipeGestureRecognizerDirection.up:
print("Swiped up")
default:
break
}
}
}

来自故事板:

  1. 在视图中添加四个滑动手势识别器。
  2. 根据属性检查器设置每个属性的目标方向 选择右,左,上或下
  3. 一个接一个,选择滑动手势识别器,控制 + 拖动到您的视图控制器。插入名称(让我们说 left Gesture,right Gesture,upGesture and (downGesture) ,将连接更改为: Action 并键入为: 手势识别器

从你的角度来看控制器:

@IBAction func rightGesture(sender: UISwipeGestureRecognizer) {
print("Right")
}
@IBAction func leftGesture(sender: UISwipeGestureRecognizer) {
print("Left")
}
@IBAction func upGesture(sender: UISwipeGestureRecognizer) {
print("Up")
}


@IBAction func downGesture(sender: UISwipeGestureRecognizer) {
print("Down")
}

我只是想把这个贡献出来,最后看起来更优雅:

func addSwipe() {
let directions: [UISwipeGestureRecognizerDirection] = [.Right, .Left, .Up, .Down]
for direction in directions {
let gesture = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
gesture.direction = direction
self.addGestureRecognizer(gesture)
}
}


func handleSwipe(sender: UISwipeGestureRecognizer) {
print(sender.direction)
}

看起来最近事情发生了变化。在 XCode 7.2中,以下方法是有效的:

override func viewDidLoad() {
super.viewDidLoad()


let swipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
swipeGesture.direction = [.Down, .Up]
self.view.addGestureRecognizer(swipeGesture)
}


func handleSwipe(sender: UISwipeGestureRecognizer) {
print(sender.direction)
}

在 iOS 8.4和9.2的 Simulator 和9.2的实际设备上进行了测试。

或者,使用 麦克科拉德的方便扩展 给你:

let swipeGesture = UISwipeGestureRecognizer() {
print("Gesture recognized !")
}


swipeGesture.direction = [.Down, .Up]
self.view.addGestureRecognizer(swipeGesture)

UISwipeGestureRecognizer具有 direction属性,其定义如下:

var direction: UISwipeGestureRecognizerDirection

这个手势识别器允许的滑动方向。


Swift 3.0.1(及以下版本)的问题在于,即使 UISwipeGestureRecognizerDirection符合 OptionSet,下面的代码片段也会编译,但不会产生任何积极的预期结果:

// This compiles but does not work
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureHandler))
gesture.direction = [.right, .left, .up, .down]
self.addGestureRecognizer(gesture)

作为解决方案,您必须为每个所需的 direction创建一个 UISwipeGestureRecognizer


下面的 Playground 代码演示了如何使用 Array 的 map方法为相同的 UIViewselector实现多个 UISwipeGestureRecognizer:

import UIKit
import PlaygroundSupport


class SwipeableView: UIView {
convenience init() {
self.init(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
backgroundColor = .red


[UISwipeGestureRecognizerDirection.right, .left, .up, .down].map({
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureHandler))
gesture.direction = $0
self.addGestureRecognizer(gesture)
})
}


func gestureHandler(sender: UISwipeGestureRecognizer) {
switch sender.direction {
case [.left]:   frame.origin.x -= 10
case [.right]:  frame.origin.x += 10
case [.up]:     frame.origin.y -= 10
case [.down]:   frame.origin.y += 10
default:        break
}
}
}


class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(SwipeableView())
}
}


let controller = ViewController()
PlaygroundPage.current.liveView = controller

Apple Swift 3.1-Xcode Version 8.3(8E162)

亚历山大 · 卡萨尼的方法的便捷方式

let directions: [UISwipeGestureRecognizerDirection] = [.up, .down, .right, .left]
for direction in directions {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(YourClassName.handleSwipe(gesture:)))
gesture.direction = direction
self.view?.addGestureRecognizer(gesture)
}


func handleSwipe(gesture: UISwipeGestureRecognizer) {
print(gesture.direction)
switch gesture.direction {
case UISwipeGestureRecognizerDirection.down:
print("down swipe")
case UISwipeGestureRecognizerDirection.up:
print("up swipe")
case UISwipeGestureRecognizerDirection.left:
print("left swipe")
case UISwipeGestureRecognizerDirection.right:
print("right swipe")
default:
print("other swipe")
}
}

它可以通过简单地声明一个函数来完成,该函数将处理所有的滑动 UISwipeGestureIdentiizer 方向。这是我的代码:

let swipeGestureRight = UISwipeGestureRecognizer(target: self, action:#selector(ViewController.respondToSwipeGesture(_:)) )
swipeGestureRight.direction = UISwipeGestureRecognizerDirection.right
self.view .addGestureRecognizer(swipeGestureRight)


let swipeGestureLeft = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeGestureLeft)


let swipeGestureUp = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureUp.direction = UISwipeGestureRecognizerDirection.up
self.view.addGestureRecognizer(swipeGestureUp)


let swipeGestureDown = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.respondToSwipeGesture(_:)))
swipeGestureDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeGestureDown)

下面的函数将提供滑动方向功能:

func respondToSwipeGesture(_ sender: UIGestureRecognizer) {
if let swipeGesture = sender as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
print("right swipe")
case UISwipeGestureRecognizerDirection.left:
print("leftSwipe")
case UISwipeGestureRecognizerDirection.up:
print("upSwipe")
case UISwipeGestureRecognizerDirection.down:
print("downSwipe")
default:
break
}
}
}

内特的回答只有一个更简洁的句法:

[UISwipeGestureRecognizerDirection.right,
UISwipeGestureRecognizerDirection.left,
UISwipeGestureRecognizerDirection.up,
UISwipeGestureRecognizerDirection.down].forEach({ direction in
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipe.direction = direction
self.view.addGestureRecognizer(swipe)
})

很简单,只要按照下面的代码就可以享受了。

//SwipeGestureMethodUsing
func SwipeGestureMethodUsing ()
{
//AddSwipeGesture
[UISwipeGestureRecognizerDirection.right,
UISwipeGestureRecognizerDirection.left,
UISwipeGestureRecognizerDirection.up,
UISwipeGestureRecognizerDirection.down].forEach({ direction in
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipe.direction = direction
window?.addGestureRecognizer(swipe)
})
}


//respondToSwipeGesture
func respondToSwipeGesture(gesture: UIGestureRecognizer) {


if let swipeGesture = gesture as? UISwipeGestureRecognizer
{
switch swipeGesture.direction
{
case UISwipeGestureRecognizerDirection.right:
print("Swiped right")
case UISwipeGestureRecognizerDirection.down:
print("Swiped down")
case UISwipeGestureRecognizerDirection.left:
print("Swiped left")
case UISwipeGestureRecognizerDirection.up:
print("Swiped up")
default:
break
}
}
}

在 Swift 4.2和 Xcode 9.4.1中

将动画委托 < em > CAAnimationLegate 添加到类中

//Swipe gesture for left and right
let swipeFromRight = UISwipeGestureRecognizer(target: self, action: #selector(didSwipeLeft))
swipeFromRight.direction = UISwipeGestureRecognizerDirection.left
menuTransparentView.addGestureRecognizer(swipeFromRight)


let swipeFromLeft = UISwipeGestureRecognizer(target: self, action: #selector(didSwipeRight))
swipeFromLeft.direction = UISwipeGestureRecognizerDirection.right
menuTransparentView.addGestureRecognizer(swipeFromLeft)


//Swipe gesture selector function
@objc func didSwipeLeft(gesture: UIGestureRecognizer) {
//We can add some animation also
DispatchQueue.main.async(execute: {
let animation = CATransition()
animation.type = kCATransitionReveal
animation.subtype = kCATransitionFromRight
animation.duration = 0.5
animation.delegate = self
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
//Add this animation to your view
self.transparentView.layer.add(animation, forKey: nil)
self.transparentView.removeFromSuperview()//Remove or hide your view if requirement.
})
}


//Swipe gesture selector function
@objc func didSwipeRight(gesture: UIGestureRecognizer) {
// Add animation here
DispatchQueue.main.async(execute: {
let animation = CATransition()
animation.type = kCATransitionReveal
animation.subtype = kCATransitionFromLeft
animation.duration = 0.5
animation.delegate = self
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
//Add this animation to your view
self.transparentView.layer.add(animation, forKey: nil)
self.transparentView.removeFromSuperview()//Remove or hide yourview if requirement.
})
}

如果要从视图中删除手势,请使用此代码

self.transparentView.removeGestureRecognizer(gesture)

例如:

func willMoveFromView(view: UIView) {
if view.gestureRecognizers != nil {
for gesture in view.gestureRecognizers! {
//view.removeGestureRecognizer(gesture)//This will remove all gestures including tap etc...
if let recognizer = gesture as? UISwipeGestureRecognizer {
//view.removeGestureRecognizer(recognizer)//This will remove all swipe gestures
if recognizer.direction == .left {//Especially for left swipe
view.removeGestureRecognizer(recognizer)
}
}
}
}
}

这个函数叫做

//Remove swipe gesture
self.willMoveFromView(view: self.transparentView)

像这样,你可以写剩余的方向,请小心,如果你有 滚动视图或不从底部到顶部,反之亦然

如果你有滚动视图,你会得到 冲突为顶部到底部和查看相反的手势。

“ Swift 5.3”

首先创建一个 baseViewController并添加 viewDidLoad这段代码:

class BaseViewController: UIViewController {


override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeRight.direction = .right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeLeft.direction = .left
self.view.addGestureRecognizer(swipeLeft)
}


// Example Tabbar 5 pages
@objc func swiped(_ gesture: UISwipeGestureRecognizer) {
if gesture.direction == .left {
if (self.tabBarController?.selectedIndex)! < 5 {
self.tabBarController?.selectedIndex += 1
}
} else if gesture.direction == .right {
if (self.tabBarController?.selectedIndex)! > 0 {
self.tabBarController?.selectedIndex -= 1
}
}
}
}

使用这个 baseController类:

class YourViewController: BaseViewController {
// its done. Swipe successful
//Now you can use all the Controller you have created without writing any code.
}

就像这样: (Swift 4.2.1)

UISwipeGestureRecognizer.Direction.init(
rawValue: UISwipeGestureRecognizer.Direction.left.rawValue |
UISwipeGestureRecognizer.Direction.right.rawValue |
UISwipeGestureRecognizer.Direction.up.rawValue |
UISwipeGestureRecognizer.Direction.down.rawValue
)

Swift 5中滑动手势

  override func viewDidLoad() {
super.viewDidLoad()
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeLeft.direction = .left
self.view!.addGestureRecognizer(swipeLeft)


let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeRight.direction = .right
self.view!.addGestureRecognizer(swipeRight)


let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeUp.direction = .up
self.view!.addGestureRecognizer(swipeUp)


let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeDown.direction = .down
self.view!.addGestureRecognizer(swipeDown)
}


@objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
if gesture.direction == UISwipeGestureRecognizer.Direction.right {
print("Swipe Right")
}
else if gesture.direction == UISwipeGestureRecognizer.Direction.left {
print("Swipe Left")
}
else if gesture.direction == UISwipeGestureRecognizer.Direction.up {
print("Swipe Up")
}
else if gesture.direction == UISwipeGestureRecognizer.Direction.down {
print("Swipe Down")
}
}

Swift 5更新了

//Add in ViewDidLoad
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.handleSwipe))
gesture.direction = .right
self.view.addGestureRecognizer(gesture)


//Add New Method
@objc func handleSwipe(sender: UISwipeGestureRecognizer) {
print("swipe direction is",sender.direction)


}

经过一段时间的调查:

添加四个方向的滑动的最短路径是:

override func viewDidLoad() {
super.viewDidLoad()
for direction in [UISwipeGestureRecognizer.Direction.down, .up, .left, .right]{
let swipeGest = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(_:)))
swipeGest.direction = direction
self.view.addGestureRecognizer(swipeGest)
}
}


@objc func swipeAction(_ gesture: UISwipeGestureRecognizer){
switch gesture.direction {
case UISwipeGestureRecognizer.Direction.right:
print("Swiped right")
case UISwipeGestureRecognizer.Direction.down:
print("Swiped down")
case UISwipeGestureRecognizer.Direction.left:
print("Swiped left")
case UISwipeGestureRecognizer.Direction.up:
print("Swiped up")
default: break
}

在基于 @ Alexandre Cassagne的 Swift 5 & XCode 11中,将手势滑动到所需的视图,或者视图控制器整个视图

override func viewDidLoad() {
super.viewDidLoad()


addSwipe()
}


func addSwipe() {
let directions: [UISwipeGestureRecognizer.Direction] = [.right, .left, .up, .down]
for direction in directions {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
gesture.direction = direction
self.myView.addGestureRecognizer(gesture)// self.view
}
}


@objc func handleSwipe(sender: UISwipeGestureRecognizer) {
let direction = sender.direction
switch direction {
case .right:
print("Gesture direction: Right")
case .left:
print("Gesture direction: Left")
case .up:
print("Gesture direction: Up")
case .down:
print("Gesture direction: Down")
default:
print("Unrecognized Gesture Direction")
}
}

在 Swift 5中,

let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeGesture.direction = [.left, .right, .up, .down]
view.addGestureRecognizer(swipeGesture)
import UIKit


class ViewController: UIViewController {


override func viewDidLoad() {
super.viewDidLoad()
let leftside = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
leftside.direction = .left
view.addGestureRecognizer(leftside)
        

let rightside = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
rightside.direction = .right
view.addGestureRecognizer(rightside)
        

        

let upside =  UISwipeGestureRecognizer(target: self, action: #selector(swiped))
upside.direction = .up
view.addGestureRecognizer(upside)
        

let downside = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
downside.direction = .down
view.addGestureRecognizer(downside)
        

// Do any additional setup after loading the view, typically from a nib.
}
@objc func swiped(gesture: UIGestureRecognizer){
if let swipeGesture = gesture as? UISwipeGestureRecognizer{
switch swipeGesture.direction{
case UISwipeGestureRecognizer.Direction.left:
view.backgroundColor = UIColor.red
case UISwipeGestureRecognizer.Direction.right:
view.backgroundColor = UIColor.yellow
case UISwipeGestureRecognizer.Direction.up:
view.backgroundColor = UIColor.green
case UISwipeGestureRecognizer.Direction.down:
view.backgroundColor = UIColor.blue
               

default:
"ERROR"
                

}
}
}


}

我用迅捷5和 xcode 13找到了识别手势的简单方法

     let gestureLeft = UISwipeGestureRecognizer(target: self, action: #selector(onLeftGesture))
gestureLeft.direction = UISwipeGestureRecognizer.Direction.left
imageView.addGestureRecognizer(gestureLeft)
    

let gestureRight = UISwipeGestureRecognizer(target: self, action: #selector(onRightGesture))
gestureRight.direction = .right
imageView.addGestureRecognizer(gestureRight)
    

let gestureUp = UISwipeGestureRecognizer(target: self, action: #selector(onUpGesture))
gestureUp.direction = .up
imageView.addGestureRecognizer(gestureUp)
    

let gestureDown = UISwipeGestureRecognizer(target: self, action: #selector(onDownGesture))
gestureDown.direction = .down
imageView.addGestureRecognizer(gestureDown)
            

let gestureTapSingle = UITapGestureRecognizer(target: self, action: #selector(onSingleTapGesture))
gestureTapSingle.numberOfTapsRequired = 1
labelGesture.addGestureRecognizer(gestureTapSingle)
    

let gestureTapDouble = UITapGestureRecognizer(target: self, action: #selector(onDoubleTapGesture))
gestureTapDouble.numberOfTapsRequired = 2
labelGesture.addGestureRecognizer(gestureTapDouble)
    

gestureTapSingle.require(toFail: gestureTapDouble)
    

let gesturePressLong = UILongPressGestureRecognizer(target: self, action: #selector(onLongPressGesture))
gesturePressLong.minimumPressDuration = 0.5
labelGesture.addGestureRecognizer(gesturePressLong)
}
@objc func onLeftGesture(_ sender: UISwipeGestureRecognizer) {
print("Left")
}


@objc func onRightGesture(_ sender: UISwipeGestureRecognizer) {
print("Right")
}


@objc func onUpGesture(_ sender: UISwipeGestureRecognizer) {
print("Up")
}


@objc func onDownGesture(_ sender: UISwipeGestureRecognizer) {
print("Down")
}
    

@objc func onSingleTapGesture(_ sender: UITapGestureRecognizer) {
print("Single Tap")
}


@objc func onDoubleTapGesture(_ sender: UITapGestureRecognizer) {
print("Double Tap")
}


@objc func onLongPressGesture(_ sender: UILongPressGestureRecognizer) {
print("Long Press Gesture!!!")
}

Swift 5 +

将所需的手势添加到某些 UIView中:

[UISwipeGestureRecognizer.Direction.up, .down, .left, .right].forEach {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
gesture.direction = $0
someView.addGestureRecognizer(gesture)
}

处理滑动动作:

@objc func swiped(_ gesture: UISwipeGestureRecognizer) {
switch gesture.direction {
case .up:       print("up")
case .down:     print("down")
case .left:     print("left")
case .right:    print("right")
default: break
}
}

2022年

以下是您可能在任何现实生活中编写的代码。

你永远不会把你的 VC 代码和所有的样板文件混在一起。

在您的视图控制器中..。

override func viewDidLoad() {
super.viewDidLoad()
pentaSceneView.buildFresh()
addSwipesLRUD(#selector(swipeLeft), #selector(swipeRight),
#selector(swipeUp), #selector(swipeDown))
}

还有..。

@objc func swipeLeft() {
blah ...
}


@objc func swipeRight() {
blah ...
}


@objc func swipeUp() {
blah ...
}


@objc func swipeDown() {
blah ...
}

你应该使用 switch 语句吗? 答案是: 不,不用。

苹果公司的 .direction代码并没有那么糟糕,只是“非常愚蠢”,而且他们一直在修改。一个 switch 语句既不比四个功能更优雅,也不比四个功能更短,而且当苹果(再一次)稍微改变或合理化 .direction的工作方式时,它很可能会中断。

下面是所需的简单扩展。

将这个文件放在项目中的任何文件中,比如“ Utils.swift”。每个真实世界的项目都有一个“扩展在这里”类型的文件,在这里,您可以保存在所有项目中使用的非常常见的扩展。

extension UIViewController {
///Add a UISwipeGestureRecognizer.
func addSwipe(_ d: UISwipeGestureRecognizer.Direction, _ s: Selector) {
let g = UISwipeGestureRecognizer(target: self, action: s)
g.direction = d
view.addGestureRecognizer(g)
}
    

///Add four swipes for left right up down.
func addSwipesLRUD(_ l: Selector, _ r: Selector, _ u: Selector, _ d: Selector) {
addSwipe(.left, l)
addSwipe(.right, r)
addSwipe(.up, u)
addSwipe(.down, d)
}
}