Copy UIImage to clipboard on tap

654 Views Asked by At

I've got a UICollectionView which displays as many cells as the amount of images passed through.

I want to make it so that when you tap an image, it copies that image to the clipboard.

Any help would be greatly appreciated.

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
             cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *Cell = [collectionView
                          dequeueReusableCellWithReuseIdentifier:@"ImagesCell"
                          forIndexPath:indexPath];

UIImage *image;
int row = indexPath.row;

//set image of this cell
image = [UIImage imageNamed:localImages.imageFiles[row]];
Cell.imageCell.image = image;


//enable touch
[Cell.imageCell setUserInteractionEnabled:YES];
Cell.imageCell.tag = row;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)];
[tapGesture setNumberOfTapsRequired:1];
[Cell.imageCell addGestureRecognizer:tapGesture];

return Cell;
}


- (void)tapGestureRecognizer:(UITapGestureRecognizer *)sender
{

NSInteger string = (sender.view.tag);
NSLog(@"this is image %i",string);

UIImage *copiedImage = I don't know what to put here..
[[UIPasteboard generalPasteboard] setImage:copiedImage];

}
1

There are 1 best solutions below

0
On

It's actually easier if you just implement the delegate method of UICollectionView - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath and just do this:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    UIImage *copiedImage = cell.imageCell.image;
    [[UIPasteboard generalPasteboard] setImage:copiedImage];
}

Hope this helped you out!

Edit: In case you have different type of cells with images and text and you only want to enable copying under images, you will have to implement that UITapGestureRecognizer part and in the method called you just need to do this:

- (void)tapGestureRecognizer:(UITapGestureRecognizer *)sender
{

UIImageView *imageView = (UIImageView *)sender.view;
UIImage *copiedImage = imageView.image;
[[UIPasteboard generalPasteboard] setImage:copiedImage];

}

Since your UITapGestureRecognizer is attached to the UIImageView, it is the sending view and you can extract the image directly from it and copy to the pasteboard.