Search code examples
iosobjective-ccalayer

In ios CAlayer Setcontents method take a single image. I have a method that change the images on touch event


CALayer *featureLayer = nil;
[featureLayer setContents:(id)[square CGImage]];

i need to change 'square' on touch from inside of array images.

- (void)viewDidLoad
{
    [super viewDidLoad];
images = [[NSArray alloc] initWithObjects:
              [UIImage imageNamed:@"ic copy2"],
              [UIImage imageNamed:@"bubble 1"],
              [UIImage imageNamed:@"bubble 2"],
              [UIImage imageNamed:@"bubble 3"],
              [UIImage imageNamed:@"bubble 4"],
              nil];
square=[images objectAtIndex:0];
//some code....}

here is the method that change image on touch event.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
      NSLog(@"'Touches Began");

    if ([touch view] == previewView) {
        square = [images objectAtIndex:1];
        NSLog(@"Image touched and changed");
    }

    currentImage++;
    NSLog(@"Touch Count = %d", currentImage);
    if (currentImage == [images count])
        currentImage = 0;

    square= [images objectAtIndex:currentImage];



}

As Setcontents make a static copy of the image so image is not changing in uiview. Is there any method to change image of addcontent on touch from array of images.?


Solution

  • You seem to slightly misunderstand pointers.

    When you first assign contents = square contents is a copy of the pointer address (not an object copy). This means that later changing the address of square does not also modify contents. They are independent pointers even if they point to the same address. You need to resassign the contents pointer after modifying the square pointer.

    square = [images objectAtIndex:currentImage];
    [featureLayer setContents:(id)[square CGImage]];