Swift - 向 UIImageView 添加触摸

Swift - Adding touch to UIImageView

我正在学习在线教程,我正在尝试将触摸检测添加到 UIImageView。我意识到这可以通过手势识别器来完成,但我有一个不同的问题,我不知道如何请求它。

基本上,我添加了一个从 imageView 的框架初始化的叠加层 UIButton。但是,由于导航栏的原因,我必须将框架向下移动 64 像素。我的 imageView 是从情节提要中添加的,但是 UIButton 是以编程方式添加的。

有没有办法不用手动添加 64 像素就可以做到这一点?这没什么大不了的,但是由于打印时 imageView 的框架是 (10, 10, 355, 450)UIButton 的框架是 (10, 74, 355, 450),这让我有点不高兴。

让我澄清一下,我想知道为什么视图控制器在以编程方式添加子视图时不考虑导航栏的大小?从 Storyboard 添加子视图时似乎可以很好地处理这个问题。

Without adding 64px:

    overlay = UIButton(frame: imageView.frame)
    overlay.backgroundColor = UIColor.red
    overlay.addTarget(self, action: #selector(imageViewTapped), for: .touchUpInside)
    view.addSubview(overlay)

With 64px added - fits perfectly

    overlay = UIButton(frame: imageView.frame.offsetBy(dx: 0, dy: 64))
    overlay.backgroundColor = UIColor.red
    overlay.addTarget(self, action: #selector(imageViewTapped), for: .touchUpInside)
    view.addSubview(overlay)

UIViewController 的导航栏设置为 Opaque Navigation Bar。它将开始您在导航栏下方查看。

您可以在图像视图上添加按钮。

试试这个:

let overlay = UIButton(frame: imageView.bounds)
        imageView.isUserInteractionEnabled = true
        overlay.backgroundColor = UIColor.red.withAlphaComponent(0.3)
        overlay.addTarget(self, action: #selector(imageViewTapped), for: .touchUpInside)
        imageView.addSubview(overlay)

您可以使用 UITapGestureRecognizer 与下面给出的相同。

    let bg = UIImageView(image: UIImage(named: "Home"))
    bg.frame = self.view.frame
    self.view.addSubview(bg)

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(SecondViewController.onTapScreen))
    bg.isUserInteractionEnabled = true
    bg.addGestureRecognizer(tapRecognizer)

如下所示处理点击事件

    func onTapScreen() {
         // Handle touch here.
    }

这样就不用再用按钮了,避免了多个控件。