1

I have an image view that has two animation images, occuring in 1-second intervals. I want to run some methods when my image view is displaying one of those two images

I already tried doing:

if(self.imageViewThatPerformsAnimation.image == [UIImage imageNamed: @"someImage"])
    [self doSomeMethod];

but when I tried this and ran it, [self doSomeMethod]; always ran, and not just when the image view was displaying that one image.

I'm thinking about having a timer that changes a boolean value every one second then saying

if (booleanValue==YES)
    [self doSomeMethod]

It's just that I feel there may be a better way.

4

1 回答 1

1

如果你想使用 a NSTimer,它可能看起来像:

@interface MyViewController ()
{
    NSTimer *_timer;
    NSArray *_images;
    NSInteger _currentImageIndex;
}
@end

@implementation MyViewController

@synthesize imageview = _imageview;

- (void)viewDidLoad
{
    [super viewDidLoad];

    _images = [NSArray arrayWithObjects:
               [UIImage imageNamed:@"imgres-1.jpg"], 
               [UIImage imageNamed:@"imgres-2.jpg"], 
               [UIImage imageNamed:@"imgres-3.jpg"], 
               [UIImage imageNamed:@"imgres-4.jpg"], 
               nil];

    _currentImageIndex = -1;
    [self changeImage];

    // Do any additional setup after loading the view.
}

- (void)changeImage
{
    _currentImageIndex++;

    if (_currentImageIndex >= [_images count])
        _currentImageIndex = 0;

    self.imageview.image = [_images objectAtIndex:_currentImageIndex];

    if (_currentImageIndex == 0)
        [self doSomething];
}

- (void)startTimer
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }

    _timer = [NSTimer timerWithTimeInterval:1.0
                                     target:self 
                                   selector:@selector(changeImage)
                                   userInfo:nil
                                    repeats:YES];

    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

- (void)stopTimer
{
    [_timer invalidate];
    _timer = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self startTimer];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    [self stopTimer];
}
于 2012-07-15T20:01:04.753 回答