Preciso usar furto para reconhecer o gesto de furto para baixo e para a direita. Mas no rápido UISwipeGestureRecognizer tem direção correta predeterminada .. E eu não sei como fazer isso para usar outras direções ..
Preciso usar furto para reconhecer o gesto de furto para baixo e para a direita. Mas no rápido UISwipeGestureRecognizer tem direção correta predeterminada .. E eu não sei como fazer isso para usar outras direções ..
Respostas:
Você precisa ter um UISwipeGestureRecognizer
para cada direção. É um pouco estranho, porque a UISwipeGestureRecognizer.direction
propriedade é uma máscara de bits no estilo de opções, mas cada reconhecedor pode lidar apenas com uma direção. Você pode enviá-los todos para o mesmo manipulador, se desejar, e classificá-los, ou enviá-los para diferentes manipuladores. Aqui está uma implementação:
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
}
}
}
Swift 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
}
}
}
UISwipeGestureRecognizerDirection
na frente do .Down
ect. Apenas usando swipeDown.direction = .Down
se for suficiente. Apenas uma dica =)
swipe.direction = [.Right,.Down,.Up,.Left]
), o reconhecedor nem será chamado, talvez esse seja um problema do swift, mas a partir de agora não funciona.
Eu apenas queria contribuir com isso, parece mais elegante no final:
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)
}
self.addGestureRecognizer(gesture)
causou um erro para mim. O que foi consertado self.view.addGestureRecognizer(gesture);
.
UIView
subclasse, mas você está absolutamente certo se estiver em um UIViewController
!
No storyboard:
Do seu viewController:
@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")
}
Parece que as coisas mudaram recentemente. No XCode 7.2, a seguinte abordagem funciona:
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)
}
Testado no Simulator no iOS 8.4 e 9.2 e no dispositivo real no 9.2.
Ou, usando a útil extensão do mlcollard aqui :
let swipeGesture = UISwipeGestureRecognizer() {
print("Gesture recognized !")
}
swipeGesture.direction = [.Down, .Up]
self.view.addGestureRecognizer(swipeGesture)
[UISwipeGestureRecognizerDirection.right, .left, .up, .down]
A maneira prática da abordagem de Alexandre Cassagne
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")
}
}
defaults write com.apple.dt.xcode IDEPlaygroundDisableSimulatorAlternateFramebuffer -bool YES
Terminal para corrigir um bug em algum hardware. Deve ser corrigido em uma nova versão do Xcode
No Swift 4.2 e no Xcode 9.4.1
Adicione delegado de animação, CAAnimationDelegate à sua turma
//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.
})
}
Se você deseja remover o gesto da vista, use este código
self.transparentView.removeGestureRecognizer(gesture)
Ex:
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)
}
}
}
}
}
Chame essa função como
//Remove swipe gesture
self.willMoveFromView(view: self.transparentView)
Assim, você pode escrever as direções restantes e tenha cuidado, se você tem a visualização de rolagem ou não de baixo para cima e vice-versa
Se você tiver a visualização de rolagem, haverá conflito de cima para baixo e exibirá os gestos.
UISwipeGestureRecognizer
possui uma direction
propriedade que possui a seguinte definição:
var direction: UISwipeGestureRecognizerDirection
A direção permitida do furto para este reconhecedor de gestos.
O problema com o Swift 3.0.1 (e abaixo) é que, mesmo se estiver em UISwipeGestureRecognizerDirection
conformidade OptionSet
, o seguinte snippet será compilado, mas não produzirá nenhum resultado esperado positivo:
// This compiles but does not work
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureHandler))
gesture.direction = [.right, .left, .up, .down]
self.addGestureRecognizer(gesture)
Como solução alternativa, você precisará criar um UISwipeGestureRecognizer
para cada desejado direction
.
O seguinte código do Playground mostra como implementar vários UISwipeGestureRecognizer
para o mesmo UIView
e o mesmo selector
usando o map
método Array :
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
UISwipeGestureRecognizerDirection(rawValue: 15)
Deslize o dedo para a visualização desejada ou visualize a visualização inteira do controlador no Swift 5 e XCode 11 com base no @Alexandre Cassagne
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")
}
}
Deslize o dedo no 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")
}
}
Primeiro crie um baseViewController
e adicione viewDidLoad
este código "swift4":
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeLeft.direction = UISwipeGestureRecognizerDirection.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
}
}
}
}
E use esta baseController
classe:
class YourViewController: BaseViewController {
// its done. Swipe successful
//Now you can use all the Controller you have created without writing any code.
}
No Swift 5,
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe))
swipeGesture.direction = [.left, .right, .up, .down]
view.addGestureRecognizer(swipeGesture)
Apenas uma sintaxe rápida e mais fria para a resposta de Nate:
[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)
})
Fácil. Basta seguir o código abaixo e aproveitar.
//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
}
}
}
Para o Swift 5 , é atualizado
//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)
}
Depois de cavar um pouco:
A maneira mais curta de adicionar furtos para todas as quatro direções é:
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
}
Isso pode ser feito simplesmente declarando uma função que manipulará todas as suas instruções UISwipeGestureRecognizer de furto. Aqui está o meu código:
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)
Aqui está a função que manipulará a funcionalidade swipedirection:
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
}
}
}
Assim: ( Swift 4.2.1 )
UISwipeGestureRecognizer.Direction.init(
rawValue: UISwipeGestureRecognizer.Direction.left.rawValue |
UISwipeGestureRecognizer.Direction.right.rawValue |
UISwipeGestureRecognizer.Direction.up.rawValue |
UISwipeGestureRecognizer.Direction.down.rawValue
)