Search code examples
xcodeios5slideshoweffectsphoto-gallery

Add transition effect in a slideshow


I'm trying to add a transition effect to my slideshow: here's my code

- (void)viewDidLoad
{
[super viewDidLoad];
photos = [[NSMutableArray alloc] init];

NSXMLParser *photoParser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL 
URLWithString:@"http://localhost/index.xml"]];
[photoParser setDelegate:(id)self];
[photoParser parse];

currentImage = 0;

NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:0]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
[imgView setImage:[UIImage imageWithData:imageData]];

timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
                                         target: self
                                       selector: @selector(handleTimer:)
                                       userInfo: nil
                                        repeats: YES];
}

- (void) handleTimer: (NSTimer *) timer {
currentImage++;
if ( currentImage >= photos.count )
    currentImage = 0;

NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:currentImage]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
[imgView setImage:[UIImage imageWithData:imageData]];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
attributes:(NSDictionary *)attributeDict { 
if ( [elementName isEqualToString:@"photo"]) {
    [photos addObject:[attributeDict objectForKey:@"url"]];
}
}

I think I should use

[UIView transitionFromView:currentView toView:nextView duration:1.0 
options:UIViewAnimationOptionTransitionCrossDissolve completion:nil];

but I don't how to fill the transitionFRomView: and toView: fields. I only have one view

Thanks for your help


Solution

  • You can use the method transitionWithView:duration:options:animations:completion: for which the documentation says:

    You can use this block to add, remove, show, or hide subviews of the specified view.

    This is an example of how you can use that method:

    - (void) handleTimer: (NSTimer *) timer {
        currentImage++;
        if (currentImage >= photos.count) currentImage = 0;
    
        NSURL *imageURL = [NSURL URLWithString:[photos objectAtIndex:currentImage]];
        NSData *imageData = [NSData dataWithContentsOfURL:imageURL]
       [UIView transitionWithView:containerView
           duration:2
           options:UIViewAnimationOptionTransitionFlipFromLeft
           animations:^{
               [imgView removeFromSuperview];
               imgView = // create a new image view
               [imgView setImage:[UIImage imageWithData:imageData]];
               [containerView addSubview:toView];
           } completion:NULL];
    }
    

    Where containerView is the parent view of imgView and most likely is self.view.