Search code examples
swifttagsimageviewappenduser-interaction

change color of uiimageview in a empty array by pressing on it


My swift code below has a button and when touch places a imageview on the viewcontroller. The only thing I want to do is when a individual imageview not all of the imageview just the one select is touch I would like to change the color from purple to blue only if touched and one at a time.

enter image description here

import UIKit

class ViewController: UIViewController {

   var count: Int = 0
   var ht = -90
   var ww = 80
   var moveCounter = 0
   var counter = 0
   var arrTextFields = [UIImageView]()
   var b7 = UIButton()


   override func viewDidLoad() {
       super.viewDidLoad()

       [b7].forEach {
           $0.translatesAutoresizingMaskIntoConstraints = false
           view.addSubview($0)
           $0.backgroundColor = .systemOrange
       }

       b7.frame = CGRect(x: view.center.x-115, y: view.center.y + 200, width: 70, height: 40)
       b7.addTarget(self, action: #selector(addBOx), for: .touchUpInside)

   }

   //func that adds imageview.
   @objc func addBOx() {

       let subview = UIImageView()

       subview.isUserInteractionEnabled = true
       arrTextFields.append(subview)
       view.addSubview(subview)


       subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: CGFloat(ww), height: 35)


       subview.backgroundColor = .purple
       subview.tag = count

       count += 1
       ht += 50
       arrTextFields.append(subview)



   }}

Solution

  • You already set the isUserInteractionEnabled property of the image view to true. To respond to touch events, create a UITapGestureRecognizer and add it to the image view like so:

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

    Then inside of the imageViewTapped method you can extract the image view from the sender argument:

    @objc func imageViewTapped(sender: UITapGestureRecognizer) {
        if let imageView = sender.view as? UIImageView {
            // Change the imageView's background here
        }
    }