Home > Software engineering >  IOS : add action to image in content extension push notification
IOS : add action to image in content extension push notification

Time:09-23

I am showing multiple images in form of a grid in my content extension. how can I add an different action for every image. I know we can add action for button. Is it possible to add action for image too.

CodePudding user response:

You can add a UITapGestureRecognizer to your image view and differentiate your images using tags like this:


Objective-C Version:

// declare tap gesture
UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];

// specify number of taps required
[imageTap setNumberOfTapsRequired:1];
        
// enable user interaction and add the tap gesture   tag for image 1
[imageview1 setUserInteractionEnabled:YES]
[imageview1 addGestureRecognizer:imageTap];
imageview1.tag = 1;
    
// enable user interaction and add the tap gesture   tag for image 2
[imageview2 setUserInteractionEnabled:YES]
[imageview2 addGestureRecognizer:imageTap];
imageview.tag = 2;
-(void)imageTapped:(UITapGestureRecognizer*)sender {
    if(sender.view.tag == 1) {
        // do something with image 1 here
    } else if (sender.view.tag == 2) {
        // do something with image 2 here
    }
}

Swift Version:

// declare tap gesture
let imageTap = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
    
// specify number of taps required
imageTap.numberOfTapsRequired = 1
                
// enable user interaction and add the tap gesture   tag for image 1
imageView1.isUserInteractionEnabled = true
imageView1.addGestureRecognizer(imageTap)
imageView1.tag = 1
            
// enable user interaction and add the tap gesture   tag for image 2
imageView2.isUserInteractionEnabled = true
imageView2.addGestureRecognizer(imageTap)
imageView2.tag = 2
@objc func imageTapped(sender: UITapGestureRecognizer) {
    
        if(sender.view!.tag == 1) {
        // do something with image 1 here
        } else if (sender.view!.tag == 2) {
        // do something with image 2 here
        }
    }

If you're trying to connect Obj-C to Swift. Add your tags in Obj-C and import your projects generated Swift header file in your Objective-C header file:

#import "ProjectName-Swift.h"

CodePudding user response:

For Swift 5 and for one image you can use easily this method.

override func viewDidAppear(_ animated: Bool) {
        let gesture = UITapGestureRecognizer(target: self, action: #selector(touchImage))
        self.imageView.isUserInteractionEnabled = true
        self.imageView.addGestureRecognizer(gesture)
    }

Then you need to put objc func in your class like below

@objc func touchImage() {
    // write your code here when touch images
    }
  • Related