Peristiwa sentuh UIView di pengontrol

98

Bagaimana saya dapat menambahkan tindakan touchbegin UIView atau tindakan sentuhan secara terprogram karena Xcode tidak disediakan dari Main.storyboard?

dhaval shah
sumber
Yang itu untuk tombol, OP ingin menambahkan acara untuk UIView
Miknash
Gunakan a UILongPressGestureRecognizerdengan minimumPressDurationset ke nol. Lihat jawaban ini. Itu tidak membutuhkan subclass atau menimpa apapun.
Suragch

Jawaban:

151

Anda harus menambahkannya melalui kode. Coba ini:

    // 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!")
        }
Miknash
sumber
1
Saya telah melakukan itu memberi saya kesalahan ketika saya mengklik uiView. Kode saya: let gesture = UITapGestureRecognizer (target: self.uiPendingView, aksi: "touchPending") self.uiPendingView.addGestureRecognizer (gesture) dan metode: func touchPending (pengirim: AnyObject) {println ("METHOD >>>>>>> >>>>>>>>>> ")}
dhaval shah
1
tambahkan saja: di "touchPending:" dan dalam fungsi itu terlihat seperti func touchPending (pengirim: UITapGestureRecognizer)
Rizwan Shaikh
1
Anda kehilangan ':' saat beraksi.
Miknash
Hai, Bagaimana saya bisa membedakan UIView mana yang diklik ketika semuanya memiliki fungsi someAction yang sama?
C Williams
Cara termudah adalah dengan menggunakan properti tag dan kemudian dalam fungsi menentukan tampilan mana yang merupakan pengirim
Miknash
72

Cepat 4/5:

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

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

Cepat 3:

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

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}
ventuz
sumber
4
2 BARIS PERTAMA HARUS DIPANGGIL DARI VIEWDIDLOAD!
Oleksandr
25

Memperbarui jawaban @ Crashalot untuk 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
    }
}
stevo.mit
sumber
19

Memperbarui jawaban @ Chackle untuk 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
    }
}
Crashalot
sumber
8

Letakkan ini di UIViewsubclass Anda (paling mudah jika Anda membuat sublcass untuk fungsi ini).

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
    }
  }
}
Chackle
sumber
@Chacle, saya memiliki lebih dari 10 Uiview di halaman saya, dan saya ingin menambahkan tindakan di beberapa Sub UIView. Jadi untuk itu apa yang harus saya ubah?
dhaval shah
Itu tergantung untuk apa Anda ingin menggunakannya. Apakah Anda ingin memberi tahu mana yang UIViewAnda tekan atau Anda ingin menangani beberapa penekanan di masing-masing UIView?
Chackle
Saya ingin acara sentuh untuk beberapa tampilan UI tertentu saja.
dhaval shah
8

Untuk cepat 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")
}
DevB2F
sumber
6

Buat outlet dari tampilan yang dibuat di StoryBoard.

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

Ganti metode touchesBegan. Ada 2 pilihan, setiap orang bisa menentukan mana yang lebih baik untuknya.

  1. Deteksi sentuhan dalam tampilan khusus.

    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. Deteksi titik sentuh pada tampilan khusus.

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

Terakhir, Anda perlu mendeklarasikan fungsi yang akan dipanggil, bergantung pada tampilan mana yang diklik pengguna.

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

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

func greenViewTapped() {
    print("greenViewTapped")
}
iAleksandr
sumber
Contoh yang sangat bagus berkat menunjukkan kepada saya !! bahwa kita juga dapat melakukan ini menggunakan touchEvent .. saya hanya tahu tombol dua arah dan gerakan .. Terima kasih +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
 }
Halo Đỗ
sumber
4

Anda dapat menggunakan cara ini: buat ekstensi

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
}

dan gunakan cara ini:

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

Hanya pembaruan untuk jawaban di atas:

Jika Anda ingin melihat perubahan dalam acara klik, yaitu Warna dari UIVIew Anda berubah setiap kali pengguna mengklik UIView kemudian lakukan perubahan seperti di bawah ini ...

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

Juga, panggil Kelas ini dari Storyboard & ViewController sebagai:

@IBOutlet weak var panVerificationUIView:ClickableUIView!
Pawan
sumber
2

Memperbarui jawaban @ stevo.mit untuk 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
    }
}
Jacob Ahlberg
sumber