向uiimage添加手势识别器

时间:2019-02-21 07:55:04

标签: ios swift uiimage uigesturerecognizer

我有图像滑块..我按照本教程进行操作:Create a Horizontal Paging UIScrollView with UIPageControl Swift 4 XCode 9,它工作正常。.

现在我想在这些图像上添加手势识别器..我试图这样做:

func createSlides() -> [banner] {

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapped))
    tapGesture.numberOfTapsRequired = 1
    tapGesture.numberOfTouchesRequired = 1

    let slide1:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
    slide1.img.image = UIImage(named: "bannerex")
    slide1.img.addGestureRecognizer(tapGesture)

    let slide2:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
    slide2.img.image = UIImage(named: "bannerex")
    slide2.img.addGestureRecognizer(tapGesture)

    let slide3:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
    slide3.img.image = UIImage(named: "bannerex")
    slide3.img.addGestureRecognizer(tapGesture)

    return [slide1, slide2, slide3]
}

@objc func tapped(_ sender: UITapGestureRecognizer){
    print("tapped")
    print(pageControl.currentPage)
}

但是它不起作用,什么也不会发生。

如何解决此问题?

import UIKit

class banner: UIView {


@IBOutlet weak var img: UIImageView!

 }

3 个答案:

答案 0 :(得分:3)

这里有两个问题:

  1. isUserInteractionEnabled默认为false
  2. 您必须为每个图像视图分配一个单独的手势识别器

解决方案

我建议不要将该代码放在isUserInteractionEnabled类本身中,而不是分别为每个图像视图将true设置为Banner。由于您似乎是从情节提要中初始化的,因此使用awakeFromNib函数应该可以正常工作:

class Banner: UIView {

    @IBOutlet weak var img: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()
        img.isUserInteractionEnabled = true
    }
 }

在您的createSlides()函数中,向每个视图添加单独的点击手势:

let slide1:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
slide1.img.image = UIImage(named: "bannerex")
slide1.img.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped)))

甚至对于扩展和无代码冗余都更好:

function tap() -> UITapGestureRecognizer {
    return UITapGestureRecognizer(target: self, action: #selector(tapped))
}

let slide1:banner = Bundle.main.loadNibNamed("banner", owner: self, options: nil)?.first as! banner
slide1.img.image = UIImage(named: "bannerex")
slide1.img.addGestureRecognizer(tap())

答案 1 :(得分:2)

UITapGestureRecognizer仅可用于单个视图,因此,如果要检测每个UITapGestureRecognizer上的敲击,则需要为每个图像创建不同的image。了解更多HERE

并且您需要将每个isUserInteractionEnabled的{​​{1}}设置为true

答案 2 :(得分:0)

Image views默认情况下忽略用户事件。如果希望图像视图也处理用户交互,请将其isUserInteractionEnabled属性的值更改为true。