1

如何检测是否UIImageview已更改,以及如何显示NSLog图像何时更改?这是我的代码:

-(void)changePhotoStatus
{
    NSArray *myArray = [NSArray arrayWithObjects:[NSString stringWithFormat:@"FasterText.png"],[NSString stringWithFormat:@"Don'tTouchText.png"],nil];

    fasttext.image = [UIImage imageNamed:[myArray objectAtIndex:arc4random() % [myArray count]]];

    if (fasttext.image == [UIImage imageNamed:@"Don'tToucText.png"]) {
        NSLog(@"cahn");
    }
}

NSTimer用来调用图像的变化。但NSLog不会出现。请帮忙。

4

3 回答 3

2

您可以按如下方式使用键值编码

- (void)registerSelfAsObserverForImageView
 {
    [imageView addObserver:self
                forKeyPath:@"image"
                   options:(NSKeyValueObservingOptionNew |
                            NSKeyValueObservingOptionOld)
                context:NULL];
}


- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context 
{
    // Put your code here to handle event of the imageview (object) changing value :)

    [super observeValueForKeyPath:keyPath
                         ofObject:object
                           change:change
                          context:context];
}

不要忘记在 dealloc 中注销或不再需要更新时

- (void)unregisterForChangeNotification
 {
     [imageView removeObserver:self forKeyPath:@"image"];
 }
于 2012-11-17T19:12:08.143 回答
1
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changePhotoStatus) userInfo:nil repeats:YES];

完成更改图像后,不要忘记invalidate计时器。

于 2012-11-17T20:40:07.160 回答
0

这是一个解决方案,假设您已正确设置视图文件...

#import "JDemoViewController.h"

@interface JDemoViewController ()

@property (nonatomic, retain) NSArray *imageNameArray;

- (void) handleTimerEventFired;

@end

@implementation JDemoViewController

@synthesize imageView = _imageView;
@synthesize imageNameArray = _imageNameArray;

- (void) dealloc
{
    self.imageView = nil;
    self.imageNameArray = nil;
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.imageNameArray = [NSArray arrayWithObjects:@"img1",@"img2",@"img3",@"img4", nil];

    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(handleTimerEventFired) userInfo:nil repeats:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void) handleTimerEventFired
{    
    NSString *tempImageName = [self.imageNameArray objectAtIndex:(arc4random()%4)];

    UIImage* image = [UIImage imageNamed:tempImageName];

    self.imageView.image = image;

    if(tempImageName == @"img3")
    {
        NSLog(@"Image 3 was Loaded !");
    }

}

@end
于 2012-11-17T19:40:47.317 回答