19

I'm trying to get the coordinates of a touch on the screen, To show a popup menu

how to use in page view controller

What am I doing wrong here?

  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
      let position = touch.locationInView(view)
      print(position)
    }
  }
LeNI
  • 1,184
  • 2
  • 10
  • 19

2 Answers2

22

In PageViewController,if you want to get pop up

In viewDidLoad:

let tap = UITapGestureRecognizer(target: self, action: "showMoreActions:")
    tap.numberOfTapsRequired = 1
    view.addGestureRecognizer(tap)

Make the page view controller inherit UIGestureRecognizerDelegate then add:

  func showMoreActions(touch: UITapGestureRecognizer) {

        let touchPoint = touch.locationInView(self.view)
        let DynamicView = UIView(frame: CGRectMake(touchPoint.x, touchPoint.y, 100, 100))
        DynamicView.backgroundColor=UIColor.greenColor()
        DynamicView.layer.cornerRadius=25
        DynamicView.layer.borderWidth=2
        self.view.addSubview(DynamicView)

}

UIPageViewController with TouchEvent

Aamir
  • 16,329
  • 10
  • 59
  • 65
user3182143
  • 9,459
  • 3
  • 32
  • 39
8

Swift 5:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let tap = UITapGestureRecognizer(target: self, action: #selector(touchedScreen(touch:)))
    view.addGestureRecognizer(tap)
}

@objc func touchedScreen(touch: UITapGestureRecognizer) {
    let touchPoint = touch.location(in: self.view)
    print(touchPoint)
}
ExeRhythm
  • 452
  • 5
  • 13