UITapGestureRecognizer not working in UIImageView

Viewed 29867

I had the following code:

UITapGestureRecognizer *showStoryTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showNewsStory:)];
[showStoryTapRecognizer setDelegate:self];
[self.storyImageView_ addGestureRecognizer:showStoryTapRecognizer];
[showStoryTapRecognizer release];

This however doesn't trigger the showNewsStory, why is this? I have enabled userInteraction in the image view.

10 Answers

add

storyImageView.isUserInteractionEnabled = true;

if you allowed 2 different gesture, you should add below code snippet. For example, you use pickerView and also you want to detect tap gesture for same pickerView.

Asks the delegate if two gesture recognizers should be allowed to recognize gestures simultaneously.

Objective C

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return true;
}

Swift

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}
    use lazy var instead of let . Here is an example.

    lazy var loginSignUpView: LoginSignUpView = {
            let lsv = LoginSignUpView()
            lsv.loginRegisterButton.addTarget(self, action: #selector(handleLoginRegistrationButton), for: .touchUpInside)
            lsv.segmentedControlForLoginRegister.addTarget(self, action: #selector(handleSegmentedControlForLoginRegister), for: .valueChanged)
            lsv.profileImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView)))

            return lsv
        }()


@objc func handleSelectProfileImageView() {
        print("Image tapped")
    }
Related