在多个图像视图上使用点击手势识别器

use tap gesture reconigzier on multiple image views

我的 swift 下面的代码在 uiview 控制器上放置了 2 个不同的图像视图。当用户点击 imageivew 时,我希望特定的 imageview 改变颜色。我不知道如何将该方法应用于多个图像视图。我想你会使用发件人方法。

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



    }
}
}

UIGestureRecognizer 将用于单个视图。因此,您需要为两个不同的视图创建两个单独的 UITapGestureRecognizer 对象。

例如:-

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

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

我试过你的代码:

在下面添加两行以启用@matt 提到的用户交互:

image1.isUserInteractionEnabled = true
image2.isUserInteractionEnabled = true

并为手势创建两个单独的对象:

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

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

输出:

编码愉快...