web-dev-qa-db-fra.com

Evénement tactile UIView dans le contrôleur

Comment puis-je ajouter une action tactile UIView ou une action tactile par programme, car Xcode ne fournit pas à partir de Main.storyboard?

59
dhaval shah

Vous devrez l'ajouter par le code. Essaye ça: 

    // 1.create UIView programmetically
    var myView = UIView(frame: CGRectMake(100, 100, 100, 100))
    // 2.add myView to UIView hierarchy
    self.view.addSubview(myView) 
    // 3. add action to myView
    let gesture = UITapGestureRecognizer(target: self, action: "someAction:")
    // or for Swift 2 +
    let gestureSwift2AndHigher = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
    self.myView.addGestureRecognizer(gesture)

    func someAction(sender:UITapGestureRecognizer){     
       // do other task
    }

    // or for Swift 3
    func someAction(_ sender:UITapGestureRecognizer){     
       // do other task
    }

    // or for Swift 4
    @objc func someAction(_ sender:UITapGestureRecognizer){     
       // do other task
    }
112
Miknash

Mise à jour pour Swift 4:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Mise à jour pour Swift 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}
39
ventuz

Mise à jour de la réponse de @ Crashalot pour Swift 3.x:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}
19
stevo.mit

Mise à jour de la réponse de @ Chackle pour Swift 2.x:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}
16
Crashalot

Mettez ceci dans votre sous-classe UIView (c'est plus facile si vous créez une sous-classe pour cette fonctionnalité).

class YourView: UIView {

  //Define your initialisers here

  override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }

  override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }

  override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }
}
6
Chackle

Pour Swift 4

@IBOutlet weak var someView: UIView!  
let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
self.someView.addGestureRecognizer(gesture)

@objc func someAction(_ sender:UITapGestureRecognizer){
    print("view was clicked")
}
5
DevB2F

Juste une mise à jour des réponses ci-dessus:

Si vous souhaitez que les modifications apparaissent dans l'événement click, c'est-à-dire que la couleur de votre UIVIew doit être modifiée à chaque fois que l'utilisateur clique sur UIView, puis effectuez les modifications ci-dessous ...

class ClickableUIView: UIView {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }

        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }

        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }

            self.backgroundColor = UIColor.whiteColor()//Color when UIView is not clicked.

}//class closes here

Appelez également cette classe à partir de Storyboard & ViewController en tant que:

@IBOutlet weak var panVerificationUIView:ClickableUIView!
1
Pawan

Swift 4.2:

@IBOutlet weak var viewLabel1: UIView!
@IBOutlet weak var viewLabel2: UIView!
  override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UITapGestureRecognizer(target: self, action: #selector(someAction(_:)))
    self.viewLabel1.addGestureRecognizer(myView)
}

 @objc func someAction(_ sender:UITapGestureRecognizer){
   viewLabel2.isHidden = true
 }
1
Hiền Đỗ

vous pouvez utiliser cette voie: create extension 

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 utiliser de cette façon:

@IBOutlet weak var testView: UIView!
testView.addTapGesture{
   // ...
}
0
Rasoul Miri

Créez des points de vente à partir de vues créées dans StoryBoard.

@IBOutlet weak var redView: UIView!
@IBOutlet weak var orangeView: UIView!
@IBOutlet weak var greenView: UIView!   

Remplacez la méthode toucheBegan. Il y a 2 options, tout le monde peut déterminer lequel est le meilleur pour lui.

  1. Détecter le toucher dans une vue spéciale.

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
         if let touch = touches.first {
            if touch.view == self.redView {
                tapOnredViewTapped()
            } else if touch.view == self.orangeView {
                orangeViewTapped()
            } else if touch.view == self.greenView {
                greenViewTapped()
            } else {
                return
            }
        }
    
    }
    
  2. Détecter le point de contact dans une vue spéciale.

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let location = touch.location(in: view)
            if redView.frame.contains(location) {
                redViewTapped()
            } else if orangeView.frame.contains(location) {
                orangeViewTapped()
            } else if greenView.frame.contains(location) {
                greenViewTapped()
            }
        }
    
    }
    

Enfin, vous devez déclarer les fonctions qui seront appelées, en fonction de la vue sur laquelle l'utilisateur a cliqué.

func redViewTapped() {
    print("redViewTapped")
}

func orangeViewTapped() {
    print("orangeViewTapped")
}

func greenViewTapped() {
    print("greenViewTapped")
}
0
iAleksandr

Mise à jour de la réponse de @ stevo.mit pour Swift 4.x:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}
0
Jacob Ahlberg