简体   繁体   中英

iOS (Swift): Location of touch event in UIButton programatically

I have a UIButton instance that I want to get the exact location of the touch even that triggers the selector attached to it.

The button is configured as follows:

private var button: UIButton!

private func setupButton() {
    button = UIButton(frame: frame)
    button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}

@objc private func buttonPressed(_ button: BounceButton) {
    // I need the location of the touch event that triggered this method.
}

What is the method for achieving the location of the touch event that triggered the buttonPressed method, please? I'm hesitant to use a UIGestureRecognizer instance as I actually have multiple buttons with different tag values that I use to do different things within the buttonPressed method.

Thanks for any suggestions.

Option 1

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  if let touch = touches.first {
     let position = touch.location(in: view)
      if button.frame.contains(position) {

      }
  }
}

Option2

add gesture and to access the button use

@objc func tapped(_ gesture:UITapGestureRecognizer)
{
    print(gesture.view?.tag)
    print(gesture.location(in: gesture.view))
}

gesture.view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM