Search code examples
iosswiftuiscrollviewuiimageviewuitapgesturerecognizer

Swift Add Image to UIImageView from User Tap


I have a ScrollView with an ImageView inside. Here a user can select a point on the image and it will print out the coordinates.

I'm also trying to add an image ("pin") to the tapped coordinate but am unsure how to...

// MARK: - Outlets
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var sharkImage: UIImageView!

// MARK: - View Did Load
override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 6.0

    scrollView.delegate = self

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))

    self.sharkImage.isUserInteractionEnabled = true
    self.sharkImage.addGestureRecognizer(tapGestureRecognizer)
}

// MARK: - Scroll View
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return sharkImage
}

// MARK: - Functions
func tapAction(sender: UITapGestureRecognizer) {
    // Get points for the UIImageView
    let touchPoint = sender.location(in: self.sharkImage)
    print(touchPoint)

    // Get points from the image itself
    let z1 = touchPoint.x * (sharkImage.image?.size.width)! / sharkImage.frame.width
    let z2 = touchPoint.y * (sharkImage.image?.size.height)! / sharkImage.frame.height
    print("Touched point (\(z1), \(z2)")

}

Solution

  • In your tapAction:

    let pin = UIImageView(frame: CGRect(x: touchPoint.x - 20, y: touchPoint.y - 20, width: 40, height: 40))
    pin.image = UIImage(named: "pin")
    sharkImage.addSubview(pin)
    

    So what I´m doing is adding a new UIImageView with the x and y from touchPoint.x and touchPoint.y into your current sharkImage.