如何在Swift中为UIImageView对象分配一个动作

如何在Swift中为UIImageView对象分配一个动作

本文介绍了如何在Swift中为UIImageView对象分配一个动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在用户点击动作时为其分配一个 UIImageView

I'm trying to assign an UIImageView to an action when the user taps it.

我知道如何为 UIButton 创建一个动作,但我怎么能模仿 UIButton 的相同行为,但是使用了 UIImageView

I know how to create an action for a UIButton, but how could I mimic the same behavior of a UIButton, but using a UIImageView?

推荐答案

你需要 UITapGestureRecognizer
设置使用此:

You'll need a UITapGestureRecognizer.To set up use this:

override func viewDidLoad()
{
    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
    imageView.isUserInteractionEnabled = true
    imageView.addGestureRecognizer(tapGestureRecognizer)
}

func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
    let tappedImage = tapGestureRecognizer.view as! UIImageView

    // Your action
}

(你可以也使用UIButton并为其分配图像,没有文本,只需连接IBAction)

(You could also use a UIButton and assign an image to it, without text and than simply connect an IBAction)

这篇关于如何在Swift中为UIImageView对象分配一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:48