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

jac*_*ert 12 ios swift

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

我想点击图片并采取行动.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.
    }


}
Run Code Online (Sandbox Code Playgroud)

Joe*_*ell 23

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

tapView.userInteractionEnabled = true;
Run Code Online (Sandbox Code Playgroud)