[英]Monitoring UIImageView for image property change
如何檢測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
不會出現。 請幫助。
您可以使用鍵值編碼,如下所示
- (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"];
}
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changePhotoStatus) userInfo:nil repeats:YES];
完成圖像更改后,請不要忘記invalidate
計時器invalidate
。
假設您已正確設置視圖文件,這是一個解決方案...
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.