本文介绍了如何在 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 对象分配一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!