How to get a CGPoint from a tapped location?

后端 未结 6 1581
青春惊慌失措
青春惊慌失措 2020-12-01 06:32

I\'m working on a graphing calculator app for the iPad, and I wanted to add a feature where a user can tap an area in the graph view to make a text box pop up displaying the

6条回答
  •  粉色の甜心
    2020-12-01 06:48

    Just want to toss in a Swift 4 answer because the API is quite different looking.

    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        if let touch = event?.allTouches?.first {
            let loc:CGPoint = touch.location(in: touch.view)
            //insert your touch based code here
        }
    }
    

    OR

    let tapGR = UITapGestureRecognizer(target: self, action: #selector(tapped))
    view.addGestureRecognizer(tapGR)
    
    @objc func tapped(gr:UITapGestureRecognizer) {
        let loc:CGPoint = gr.location(in: gr.view)  
        //insert your touch based code here
    }
    

    In both cases loc will contain the point that was touched in the view.

提交回复
热议问题