iOS/Swift UIImageView (.jpg) not recognizing my ta

2019-03-01 18:41发布

问题:

I have a simple block of code to play a sound when my image gets tapped. However, when I tap my image, the tap isn't even recognized.

I believe this to be true because println in the handleTap function doesn't print anything when the image is tapped.

Can anyone give me some insight as to where the problem might be?

var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("wavSampleSound", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    loadSound()

    let gesture = UITapGestureRecognizer(target: self, action: "handleTap:")
    gesture.delegate = self
    myImage.addGestureRecognizer(gesture)
}
func loadSound() {
    audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
    audioPlayer.prepareToPlay()

}
func handleTap(gesture: UITapGestureRecognizer) {
    let playsSound = self.audioPlayer.play()
    println("\(playsSound)")
}


@IBOutlet weak var myImage: UIImageView!

}

回答1:

Note that the default setting of the userInteractionEnabled of UIImageView is false. You want to set it to true.