J'ai un UIView et j'y ai ajouté un geste:
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
tap.delegate = self
myView.addGesture(tap)
J'essaie de l'appeler par programme dans le fichier de test.
sendActionForEvent
J'utilise cette fonction, mais ça ne marche pas:
myView.sendActionForEvent(UIEvents.touchUpDown)
Il montre le sélecteur non reconnu envoyé à l'instance.
Comment puis-je résoudre ce problème?
Merci d'avance
Vous devez initialiser UITapGestureRecognizer
avec une cible et une action, comme ceci:
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
tap.delegate = self // This is not required
myView.addGestureRecognizer(tap)
Ensuite, vous devez implémenter le gestionnaire, qui sera appelé chaque fois qu'un événement tap se produit:
@objc func handleTap(sender: UITapGestureRecognizer? = nil) {
// handling code
}
Alors maintenant, appeler votre gestionnaire d'événement de reconnaissance de gestes tactiles est aussi simple que d'appeler une méthode:
handleTap()
Pour ceux qui recherchent Swift 3 solution
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
view.addGestureRecognizer(tap)
view.isUserInteractionEnabled = true
self.view.addSubview(view)
// function which is triggered when handleTap is called
func handleTap(_ sender: UITapGestureRecognizer) {
print("Hello World")
}
Juste une note - N'oubliez pas d'activer l'interaction sur la vue:
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
view.addGestureRecognizer(tap)
// view.userInteractionEnabled = true
self.view.addSubview(view)
Pour Swift 4:
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
view.addGestureRecognizer(tap)
view.isUserInteractionEnabled = true
self.view.addSubview(view)
// function which is triggered when handleTap is called
@objc func handleTap(_ sender: UITapGestureRecognizer) {
print("Hello World")
}
Dans Swift 4, vous devez indiquer explicitement que la fonction déclenchée est appelable à partir d’Objective-C. Vous devez donc ajouter @objc également à votre fonction handleTap.
Voir la réponse de @ALi Beadle ici: Swift 4 ajouter un geste: override vs @objc
ÉTAPE 1
@IBOutlet var viewTap: UIView!
ÉTAPE 2
var tapGesture = UITapGestureRecognizer()
ÉTAPE 3
override func viewDidLoad() {
super.viewDidLoad()
// TAP Gesture
tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.myviewTapped(_:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
viewTap.addGestureRecognizer(tapGesture)
viewTap.isUserInteractionEnabled = true
}
ÉTAPE 4
func myviewTapped(_ sender: UITapGestureRecognizer) {
if self.viewTap.backgroundColor == UIColor.yellow {
self.viewTap.backgroundColor = UIColor.green
}else{
self.viewTap.backgroundColor = UIColor.yellow
}
}
SORTIE
Mise en œuvre du geste du robinet
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "touchHappen")
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)
Appelle cette fonction lorsque le tap est reconnu.
func touchHappen() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
self.view.endEditing(true)
}
Mise à jour pour For Swift 3
let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchHappen(_:)))
view.addGestureRecognizer(tap)
view.userInteractionEnabled = true
func touchHappen(_ sender: UITapGestureRecognizer) {
print("Hello Museer")
}
Swift 4
let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchTapped(_:)))
self.view.addGestureRecognizer(tap)
@objc func touchTapped(_ sender: UITapGestureRecognizer) {
}
Voici comment cela fonctionne dans Swift 3:
@IBOutlet var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action:#selector(handleTap))
myView.addGestureRecognizer(tap)
}
func handleTap() {
print("tapped")
}
J'ai travaillé sur Xcode 6.4 sur Swift. Voir ci-dessous.
var view1: UIView!
func assignTapToView1() {
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
// tap.delegate = self
view1.addGestureRecognizer(tap)
self.view .addSubview(view1)
...
}
func handleTap() {
print("tap working")
view1.removeFromSuperview()
// view1.alpha = 0.1
}
Vous devez initialiser UITapGestureRecognizer avec une cible et une action, comme suit:
let tap = UITapGestureRecognizer(target: self, action: "handleTap:")
tap.delegate = self
myView.addGestureRecognizer(tap)
Ensuite, vous devez implémenter le gestionnaire, qui sera appelé chaque fois qu'un événement tap se produit:
func handleTap(sender: UITapGestureRecognizer) {
// handling code
}
let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
frontView.addGestureRecognizer(tap)
// Make sure this is not private
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
}
Si vous voulez le code Objective C est donné ci-dessous,
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; // Declare the Gesture.
gesRecognizer.delegate = self;
[yourView addGestureRecognizer:gesRecognizer]; // Add Gesture to your view.
// Declare the Gesture Recognizer handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
NSLog(@"Tapped");
}
ou vous voulez le code Swift est donné ci-dessous,
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Add tap gesture recognizer to view
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
myView.addGestureRecognizer(tapGesture)
}
// this method is called when a tap is recognized
func handleTap(sender: UITapGestureRecognizer) {
print("tap")
}
}
Swift 4
Tout d'abord, créez un objet de UITapGestureRecognizer
var tapGesture = UITapGestureRecognizer()
La deuxième étape consiste à initialiser UITapGestureReconizer. Activer l'utilisateur interaction, puis ajoutez-le.
override func viewDidLoad() {
super.viewDidLoad()
tapGesture = UITapGestureRecognizer(target: self, action: #selector(YourViewController.myviewTapped(_:)))
infosView.isUserInteractionEnabled = true
infosView.addGestureRecognizer(tapGesture)
view.addSubview(infosView)
}
Troisièmement, créer une méthode
@objc func myviewTapped(_ recognizer: UIGestureRecognizer) {
print("button is tapped")
}
Réponse complète pour Swift 4
Étape 1: créer un point de vente pour la vue
@IBOutlet weak var rightViewOutlet: UIView!
Étape 2: définir un geste de tapotement
var tapGesture = UITapGestureRecognizer()
Étape 3: création de la fonction ObjC (appelée lorsque la vue est exploitée)
@objc func rightViewTapped(_ recognizer: UIGestureRecognizer) {
print("Right button is tapped")
}
Étape 4: ajoutez les éléments suivants dans viewDidLoad ()
let rightTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.rightViewTapped(_:)))
rightViewOutlet.addGestureRecognizer(rightTap)
J'ai travaillé sur Xcode 7.3.1 sur Swift 2.2. Voir ci-dessous.
func addTapGesture() {
let tap = UITapGestureRecognizer(target: self, action: #selector(MyViewController.handleTap))
tap.numberOfTapsRequired = 1
self.myView.addGestureRecognizer(tap)
}
func handleTap() {
// Your code here...
}
essayez l'extension suivante
extension UIView {
func addTapGesture(action : @escaping ()->Void ){
let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
tap.action = action
tap.numberOfTapsRequired = 1
self.addGestureRecognizer(tap)
self.isUserInteractionEnabled = true
}
@objc func handleTap(_ sender: MyTapGestureRecognizer) {
sender.action!()
}
}
class MyTapGestureRecognizer: UITapGestureRecognizer {
var action : (()->Void)? = nil
}
et ensuite l'utiliser:
submitBtn.addTapGesture {
//your code
}
vous pouvez même l'utiliser pour la cellule
cell.addTapGesture {
//your code
}
xCode 9.3, Swift 4.0
class BaseVC: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var iView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let clickUITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onSelect(_:)))
clickUITapGestureRecognizer.delegate = self
iView?.addGestureRecognizer(tap)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return true
}
@IBAction func onSelect(_ sender: Any) {
}
}
Essayez le code Swift suivant (testé dans Xcode 6.3.1):
import UIKit
class KEUITapGesture150427 : UIViewController {
var _myTap: UITapGestureRecognizer?
var _myView: UIView?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor();
_myTap = UITapGestureRecognizer(target: self
, action: Selector("_myHandleTap:"))
_myTap!.numberOfTapsRequired = 1
_myView = UIView(frame: CGRectMake(100, 200, 100, 100))
_myView!.backgroundColor=UIColor.blueColor()
_myView!.layer.cornerRadius = 20
_myView!.layer.borderWidth = 1
_myView!.addGestureRecognizer(_myTap!)
view.addSubview(_myView!)
}
func _myHandleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
println("_myHandleTap(sender.state == .Ended)")
sender.view!.backgroundColor
= UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0);
}
}
}
Notez que votre cible peut être n’importe quelle sous-classe de UIResponder, voir (testé dans Xcode 6.3.1):
import UIKit
class MyTapTarget : UIResponder {
func _myHandleTap2(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
println("_myHandleTap2(sender.state == .Ended)")
sender.view!.backgroundColor
= UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0);
}
}
}
class KEUITapGesture150427b : UIViewController {
var _myTap: UITapGestureRecognizer?
var _myView: UIView?
var _myTapTarget: MyTapTarget?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor();
_myTapTarget = MyTapTarget()
_myTap = UITapGestureRecognizer(target: _myTapTarget!
, action: Selector("_myHandleTap2:"))
_myTap!.numberOfTapsRequired = 1
_myView = UIView(frame: CGRectMake(100, 200, 100, 100))
_myView!.backgroundColor=UIColor.blueColor()
_myView!.layer.cornerRadius = 20
_myView!.layer.borderWidth = 1
_myView!.addGestureRecognizer(_myTap!)
view.addSubview(_myView!)
}
}
Je voulais préciser deux points qui me posaient des problèmes.
Inside ViewDidLoad
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
self.imgMainAdView.isUserInteractionEnabled = true
self.imgMainAdView.addGestureRecognizer(tapGestureRecognizer)
//MARK: - Image Tap Method -
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
print("Tapped")
if let url = URL(string: self.strMAinAdvLink)
{
UIApplication.shared.open(url, options: [:])
}
}
Finalité de l'appel
@IBAction func btnCall1Action(_ sender: Any)
{
let text = self.strPhoneNumber1!
let test = String(text.filter { !" -()".contains($0) })
UIApplication.shared.openURL(NSURL(string: "tel://\(test)")! as URL)
}
Objet du courrier
MFMailComposeViewControllerDelegate
@IBAction func btnMailAction(_ sender: Any)
{
let strEmail = SAFESTRING(str: (self.dictEventDetails?.value(forKeyPath: "Email.value_text.email") as! String))
if !MFMailComposeViewController.canSendMail()
{
AppDelegate.sharedInstance().showAlertAction(strTitle: "OK", strMessage: "Mail services are not available") { (success) in
}
return
}
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
composeVC.setToRecipients([strEmail])
composeVC.setSubject("")
composeVC.setMessageBody("", isHTML: false)
self.present(composeVC, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)
{
controller.dismiss(animated: true, completion: nil)
}
Voici le moyen le plus simple d’ajouter des gestes dans View dans Swift 5
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addGestures()
}
// MARK: Add Gestures to target view
func addGestures()
{
// 1. Single Tap or Touch
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGetstureDetected))
tapGesture.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGesture)
//2. Double Tap
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapGestureDetected))
doubleTapGesture.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTapGesture)
//3. Swipe
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGetstureDetected))
view.addGestureRecognizer(swipeGesture)
//4. Pinch
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(self.pinchGetstureDetected))
view.addGestureRecognizer(pinchGesture)
//5. Long Press
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGetstureDetected))
view.addGestureRecognizer(longPressGesture)
//6. Pan
let panGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.panGestureDetected))
view.addGestureRecognizer(panGesture)
}
// MARK: Handle Gesture detection
@objc func swipeGetstureDetected() {
print("Swipe Gesture detected!!")
}
@objc func tapGetstureDetected() {
print("Touch/Tap Gesture detected!!")
}
@objc func pinchGetstureDetected() {
print("Pinch Gesture detected!!")
}
@objc func longPressGetstureDetected() {
print("Long Press Gesture detected!!")
}
@objc func doubleTapGestureDetected() {
print("Double Tap Gesture detected!!")
}
@objc func panGestureDetected()
{
print("Pan Gesture detected!!")
}
//MARK: Shake Gesture
override func becomeFirstResponder() -> Bool {
return true
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){
if motion == .motionShake
{
print("Shake Gesture Detected")
}
}
}
Swift 5.1 Exemple pour trois vues
Étape: 1 -> Ajouter une vue de scénario et ajouter une vue de sortieContrôleur UIView
@IBOutlet var firstView: UIView!
@IBOutlet var secondView: UIView!
@IBOutlet var thirdView: UIView!
Étape: 2 -> Ajouter une vue storyBoard Tag
Étape: 3 -> Ajouter un geste
override func viewDidLoad() {
super.viewDidLoad()
firstView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
firstView.isUserInteractionEnabled = true
secondView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
secondView.isUserInteractionEnabled = true
thirdView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tap(_:))))
thirdView.isUserInteractionEnabled = true
}
Étape: 4 -> sélectionnez une vue.
@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
let tag = gestureRecognizer.view?.tag
switch tag! {
case 1 :
print("select first view")
case 2 :
print("select second view")
case 3 :
print("select third view")
default:
print("default")
}
}
Au lieu d’appeler UITapGestureRecognizer de myView, vous pouvez appeler directement la fonction handleTap
,
Exemple:
let tapComments = UITapGestureRecognizer(target: self, action: #selector(goToComments))
labelComments.isUserInteractionEnabled = true
labelComments.addGestureRecognizer(tapComments)
func:
@objc func goToComments(){
}