Yana
Yana

Reputation: 39

how to transfer coordinates to display a imageview with long tap

I am trying to do a task. I need a image to be displayed when I click long tap. The problem is that I don’t know how to display it where I clicked.

My code:

let longRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressHappened))
    view.addGestureRecognizer(longRecognizer)

 @objc func longPressHappened() {
    let imageView = UIImageView(image: UIImage(named: "location")!)
    imageView.frame = CGRect(x: 200, y: 100, width: 24, height: 42)
    CSimageView.addSubview(imageView)
  }

I found this code, but I don’t understand how to apply it in my problem:

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

Now long tap works, but displays at the coordinates indicated in the code, for x the number is 200, for y the number is 100. And I need the picture to appear where I clicked.

Upvotes: 0

Views: 43

Answers (1)

Saifan Nadaf
Saifan Nadaf

Reputation: 1775

Try the below code where you long tap there an image will be added.

I have added gesture and image on view.

override func viewDidLoad() {

      let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
       self.view.addGestureRecognizer(longPressRecognizer)

}


//This method will get called when you long press
    @objc func longPressed(gesture: UILongPressGestureRecognizer)
    {
        //get location of gesture
        let tapLocation = gesture.location(in: self.view)
        let imageView = UIImageView(image: UIImage(named: "location"))

        //Set x and y of tapped location
        imageView.frame = CGRect(x: tapLocation.x, y: tapLocation.y, width: 24, height: 24)
        print("longpressed")

         //Add image When lognpress is finish
        if gesture.state == .ended {
            self.view.addSubview(imageView)
        }
    }

Upvotes: 1

Related Questions