如何在Swift中识别UIImage数组中的Tapped UIImage

时间:2017-06-08 13:26:47

标签: ios swift uiscrollview uiimage uigesturerecognizer

我使用代码填充UIImage数组并成功将它们添加到UIScrollView中。我想识别点击的图像,以便我可以相应地执行操作。

感谢您的指导和时间。

这是我到目前为止的代码:

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
    }

    func loadImagePicker(){

    var contentWidth: CGFloat = 0.0
    let imageWidth: CGFloat = 100.0
    let imageHeight: CGFloat = 100.0

    for x in 0...2 {
        let image = UIImage(named: "item\(x).png")
        let imageView = UIImageView(image: image)
        imageView.isUserInteractionEnabled = true
        myData.images1.append(imageView)

        var newX: CGFloat = 0.0

        newX = 10 + imageWidth * CGFloat(x) + (10 * CGFloat(x))

        contentWidth += newX

        scrollView.addSubview(imageView)

        imageView.frame = CGRect(x: newX, y: scrollView.frame.size.height, width: imageWidth, height: imageHeight)
        imageView.contentMode = .scaleToFill
    }

    print(myData.images1.count)

    scrollView.clipsToBounds = false
    scrollView.contentSize = CGSize(width: contentWidth, height: scrollView.frame.size.height)

    imagePickerView.isHidden = false
}

2 个答案:

答案 0 :(得分:2)

为您的imageView添加手势识别器,如下所示:

    //Instance Variable
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
    tapGestureRecognizer.numberOfTapsRequired = 1
    tapGestureRecognizer.numberOfTouchesRequired = 1

    func loadImagePicker(){

        // .....

        for 0..<2 { //Assuming there are two images

        // .....
        // .....

        imageView.addGestureRecognizer(tapGestureRecognizer)

        }
    }

    func imageTapped(_ sender: UITapGestureRecognizer) {

        let tappedImageView = sender.view as! UIImageView
        let index = tappedImageView.tag // Do anything with the index by using it in your array

    }

答案 1 :(得分:0)

  1. 将您的tapGestureRecognizer设为全局或将其移至loadImagePicker功能。

  2. isUserInteractionEnabled设置为true后,添加手势 通过调用imageView的识别器 imageView.addGestureRecognizer(tapGestureRecognizer)

  3. 然后实现imageTapped函数,该函数接受UITapGestureRecognizer
  4. 类型的发件人
  5. 最后在imageTapped函数中,通过调用sender as? UIImageView
  6. 访问被点击的UIImageView