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

时间:2019-12-16 01:11:50

标签: swift imageview uitapgesturerecognizer sender

我下面的快速代码在uiview控制器上放置了2个不同的图像视图。当用户点击图像时,我希望该特定图像视图更改颜色。我不知道如何将方法应用于多个图像视图。我认为您会使用sender方法。

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



    }
}
}

2 个答案:

答案 0 :(得分:0)

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

例如:-

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

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

答案 1 :(得分:0)

我尝试了您的代码:

在下面两行添加以实现@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)

输出: enter image description here

快乐的编码...