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

How to assign an action for UIImageView object in Swift(如何在 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)
}

@objc 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 对象分配一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)