如何检测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
不会出现。请帮助。
答案 0 :(得分: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"];
}
答案 1 :(得分:1)
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changePhotoStatus) userInfo:nil repeats:YES];
完成图像更改后,请不要忘记invalidate
计时器。
答案 2 :(得分: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