如何使用swift为图像添加点按手势

时间:2022-10-30 14:54:25

I know this is quite basic, I'm starting out with swift and I couldn't find a working example.

我知道这是非常基本的,我开始使用swift,我找不到一个有效的例子。

I'd like to tap an image and do an action. The IBOutlet is linked to an image on the Main Storyboard. When I tap it, I get nothing. I was expecting to get a console message. What am I doing wrong?

我想点击图片并采取行动。 IBOutlet链接到主故事板上的图像。当我点击它时,我什么都没得到。我期待得到一个控制台消息。我究竟做错了什么?

import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var tapView: UIImageView!
    let tapRec = UITapGestureRecognizer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        tapRec.addTarget(self, action: "tappedView")
        tapView.addGestureRecognizer(tapRec)

    }

    func tappedView(){
        println("image tapped")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

1 个解决方案

#1


17  

I believe you need to enable user interaction on a UIImageView. Its set to false by default. Try:

我相信你需要在UIImageView上启用用户交互。默认设置为false。尝试:

tapView.userInteractionEnabled = true;

#1


17  

I believe you need to enable user interaction on a UIImageView. Its set to false by default. Try:

我相信你需要在UIImageView上启用用户交互。默认设置为false。尝试:

tapView.userInteractionEnabled = true;