Swift - 向UIImageView添加触摸
问题描述:
我在线上学习了一个教程,我试图将触摸检测添加到UIImageView
。我意识到这可以用一个手势识别器来完成,但我有一个不同的问题,我不知道如何去请求它。Swift - 向UIImageView添加触摸
基本上,我添加了从imageView的框架初始化覆盖UIButton
。但是,由于导航栏的原因,我必须将帧向下移动64 px。我的imageView是从故事板添加的,但是UIButton
是以编程方式添加的。
有没有办法做到这一点,而无需手动添加64像素?这并不是什么大问题,但是由于imageView的框架在打印时是(10, 10, 355, 450)
而UIButton
的框架是(10, 74, 355, 450)
,所以它有点让我觉得有些不舒服。
让我澄清,我想知道为什么视图控制器没有考虑到以编程方式添加子视图时导航栏的大小?当从Storyboard添加子视图时,它似乎处理得很好。
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)
答
您可以在图像视图中添加按钮。
试试这个:
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
的一样。下面
func onTapScreen() {
// Handle touch here.
}
给出
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)
柄敲击事件通过这种方式,你不也需要使用按钮,这样可避免多个控件。
你能显示你的UIViewController的属性检查器捕获吗? – nynohu
对不起,我现在不能添加2个以上的链接,但一切都设置为默认设置的大小:推断,状态栏:推断,顶栏:推断和底栏:推断。 –
您可以使用self.view.frame中给出的答案,请检查答案。 –