通过按下它来更改空数组中 uiimageview 的颜色

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

我下面的 swift 代码有一个按钮,触摸时会在 viewcontroller 上放置一个图像视图。我唯一想做的是当一个单独的 imageview 而不是所有的 imageview 只有一个 select 是触摸时我想将颜色从紫色更改为蓝色只有在触摸时并且一次一个。

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 {
           [=10=].translatesAutoresizingMaskIntoConstraints = false
           view.addSubview([=10=])
           [=10=].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)



   }}

您已经将图像视图的 isUserInteractionEnabled 属性 设置为 true。要响应触摸事件,请创建一个 UITapGestureRecognizer 并将其添加到图像视图中,如下所示:

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

然后在 imageViewTapped 方法中,您可以从 sender 参数中提取图像视图:

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