swiftimageviewuitapgesturerecognizersender

use tap gesture reconigzier on multiple image views


My swift code below places 2 different image views on a uiview controller. When the user hits a imageivew I want that specific imageview to change color. I dont know how to apply the method to multiple image views. I think you would use the sender method.

import UIKit

class ViewController: UIViewController {
var slider = UISlider()
var image1 = UIImageView()
var image2 = UIImageView()
var with = 80

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    [slider,image1,image2].forEach{
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
        $0.backgroundColor = .systemOrange
    }

    slider.frame = CGRect(x: view.center.x-115, y: view.center.y+200, width: CGFloat(with), height: 30)
    image1.frame = CGRect(x: view.center.x-115, y: view.center.y, width: CGFloat(with), height: 30)
    image2.frame = CGRect(x: view.center.x-115, y: view.center.y-200, width: CGFloat(with), height: 30)

    slider.minimumValue = 10
    slider.maximumValue = 150



    image1.isUserInteractionEnabled = true


    let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
    image1.addGestureRecognizer(gestureRecognizer)
    image2.addGestureRecognizer(gestureRecognizer)



}


@objc func imageViewTapped(sender: UITapGestureRecognizer) {
    if let imageView = sender.view as? UIImageView {

        imageView.backgroundColor = .yellow



    }
}
}

Solution

  • I tried your code:

    add below two lines to enable the user interaction as mentioned by @matt:

    image1.isUserInteractionEnabled = true
    image2.isUserInteractionEnabled = true
    

    and create two separate objects for gesture:

    let gestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
    image1.addGestureRecognizer(gestureRecognizer1)
    
    let gestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
    image2.addGestureRecognizer(gestureRecognizer2)
    

    Output: enter image description here

    Happy coding...