Iphone 监视图像属性更改的UIImageView
如何检测Iphone 监视图像属性更改的UIImageView,iphone,objective-c,ios,xcode,Iphone,Objective C,Ios,Xcode,如何检测UIImageview是否更改,以及图像更改时如何显示NSLog?这是我的密码: -(void)changePhotoStatus { NSArray *myArray = [NSArray arrayWithObjects:[NSString stringWithFormat:@"FasterText.png"],[NSString stringWithFormat:@"Don'tTouchText.png"],nil]; fasttext.image = [UIIm
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"];
}
这里有一个解决方案,假设您已正确设置视图文件
#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
更改完图像后,不要忘记使计时器失效。仔细检查nstimer代码。或者,如果计时器启动,则无需使其失效。只有在你想阻止它开火的时候才可以。@CameronLowellPalmer请检查这篇文章——这篇文章几乎完全是苹果定时器编程主题的副本。正如它所说的,如果它是重复的,你需要自己使它无效。然而,它是否无效取决于具体情况。
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changePhotoStatus) userInfo:nil repeats:YES];