【问题标题】:Swift - Adding touch to UIImageViewSwift - 为 UIImageView 添加触摸
【发布时间】:2017-01-10 05:57:59
【问题描述】:

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

基本上,我添加了一个覆盖UIButton,从imageView的框架初始化。但是,由于导航栏,我必须将框架向下移动 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 的属性检查器捕获吗?
  • 很抱歉,我现在不能添加超过 2 个链接,但所有内容都设置为默认设置,大小为:推断,状态栏:推断,顶栏:推断,底栏:推断。
  • 您可以使用答案中给出的 self.view.frame 请检查答案。
  • 如果imageView显示正确,尝试添加overlay作为imageView的subView而不是self.view。
  • 我应该提到,imageView 是从情节提要中添加的,并嵌入了导航控制器。但是,我想添加一个 UIButton 实例以覆盖到 imageview 但我必须手动添加 64px

标签: ios swift xcode uibutton navigationbar


【解决方案1】:

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

试试这个:

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)

【讨论】:

    【解决方案2】:

    您可以使用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.
        }
    

    通过这种方式,您也不需要使用按钮,因此可以避免多个控件。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 1970-01-01
        相关资源
        最近更新 更多