UIImageView当用户点击它时,我正在尝试分配一个动作。
UIImageView
我知道如何为 a 创建一个动作UIButton,但我怎么能模仿 a 的相同行为UIButton,但使用 a UIImageView?
UIButton
你需要一个UITapGestureRecognizer. 要设置使用这个:
UITapGestureRecognizer
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 }
(您也可以使用 aUIButton并为其分配一个图像,不带文本,而不是简单地连接 a IBAction)
IBAction