Denetleyicide UIView dokunma etkinliği


99

Xcode Main.storyboard'dan sağlanmadığı için programlı olarak UIView touchbegin eylemini veya touchend eylemini nasıl ekleyebilirim?


Bu düğme için, OP UIView için etkinlik eklemek istiyor
— Miknash

Bir kullan UILongPressGestureRecognizerile minimumPressDurationsıfıra seti. Bu cevaba bakın. Alt sınıflandırma veya herhangi bir şeyi geçersiz kılma gerektirmez.
— Suragch

Yanıtlar:


153

Kod aracılığıyla eklemeniz gerekecek. Bunu dene:

    // 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
    }

    // update for Swift UI

    Text("Tap me!")
        .tapAction {
             print("Tapped!")
        }

1
UiView'a tıkladığımda bana bir hata veriyor. Kodum: let jest = UITapGestureRecognizer (target: self.uiPendingView, action: "touchPending") self.uiPendingView.addGestureRecognizer (hareket) ve yöntem: func touchPending (gönderen: AnyObject) {println ("YÖNTEM >>>>>>> >>>>>>>>>> ")}
— dhaval shah

1
sadece şunu ekleyin: "touchPending:" ve işlevde func touchPending (gönderen: UITapGestureRecognizer)
— Rizwan Shaikh

1
eylemde ':' eksik.
— Miknash

Merhaba, Hepsi aynı bazıAction işlevine sahipken hangi UIView’ün tıklandığını nasıl ayırt edebilirim?
— C Williams

En kolay yol etiket özelliğini kullanmak ve ardından hangi görünümün gönderenin olduğunu işlevde belirlemektir
— Miknash

76

Hızlı 4/5:

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

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

Swift 3:

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

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

4
VIEWDIDLOAD'DAN İLK 2 HAT ÇAĞRILMALIDIR!
— Oleksandr

26

@ Crashalot'un Swift 3.x için cevabı güncelleniyor:

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

@ Chackle'ın Swift 2.x için cevabını güncelleme:

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
    }
}

8

UIViewBunu alt sınıfınıza koyun (bu işlevsellik için bir alt sınıf yaparsanız en kolayı budur).

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
    }
  }
}

@Chacle, sayfamda 10'dan fazla Uiview var ve bazı Sub UIView'lara eylem eklemek istiyorum. Peki bunun için neyi değiştirmeliyim?
— dhaval shah

Onu ne için kullanmak istediğine bağlı. Hangisine UIViewbastığınızı mı söylemek istersiniz yoksa her birinde birkaç baskı yapmak ister misiniz UIView?
— Chackle

Touchevent'i yalnızca bazı özel UI görünümleri için istiyorum.
— dhaval shah

8

Swift 4 için

@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")
}

6

StoryBoard'da oluşturulan görünümlerden satış noktaları oluşturun.

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

TouchesBegan yöntemini geçersiz kılın. 2 seçenek var, herkes onun için hangisinin daha iyi olduğunu belirleyebilir.

  1. Özel görünümde dokunmayı algılayın.

    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. Özel görünümde temas noktasını tespit edin.

    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()
            }
        }
    
    }
    

Son olarak, kullanıcının hangi görünüme tıkladığına bağlı olarak çağrılacak işlevleri bildirmeniz gerekir.

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

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

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

Bana gösterdiğin için çok güzel bir örnek !! bunu touchEvent kullanarak da yapabileceğimizi .. yalnızca iki yönlü düğme ve hareketi biliyorum .. Teşekkürler +1
— Yogesh Patel

5

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
 }

4

bu şekilde kullanabilirsiniz: uzantı oluşturun

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
}

ve şu şekilde kullanın:

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

2

Sadece yukarıdaki cevaplara bir güncelleme:

Tıklama olayındaki değişiklikleri görmek istiyorsanız, yani kullanıcı UIView'a her tıkladığında UIVIew shud renginizin değişmesini istiyorsanız, ardından aşağıdaki gibi değişiklikler yapın ...

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

Ayrıca, Storyboard & ViewController'daki bu Sınıfı şu şekilde adlandırın:

@IBOutlet weak var panVerificationUIView:ClickableUIView!

2

@ Stevo.mit'in Swift 4.x için cevabı güncelleniyor:

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
    }
}
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.