问题是这样的:我的类NKIngredient
是UIImageView
. 我已经实现了其中的touchesBegan/Moved/Ended
方法并设置了userInteractionEnabled
on YES
。但主要问题是,当我NKIngredient
在视图控制器中为我的实例设置动画时,我需要在动画期间可以触摸对象。这是不可能的!的接口NKIngredient
:
@protocol NKIngredientDelegate <NSObject>
- (void)ingredientTouched;
@end
@interface NKIngredient : UIImageView {
CGPoint touchStart;
}
@property (weak, nonatomic) id <NKIngredientDelegate> delegate;
- (void)animate:(void (^)(void))animationBlock;
@end
实施文件:
@implementation NKIngredient
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setUserInteractionEnabled:YES];
}
return self;
}
//Viene chiamato questo metodo se l'oggetto è disegnato come nib
- (id)initWithCoder:(NSCoder *)aDecoder {
NSLog(@"NKIngredient initWithCoder");
if (self = [super initWithCoder:aDecoder]) {
[self setUserInteractionEnabled:YES];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
- (BOOL)becomeFirstResponder {
return YES;
}
- (void)animate:(void (^)(void))animationBlock {
[UIView animateWithDuration:8.0 delay:0.0 options:UIViewAnimationOptionAllowAnimatedContent & UIViewAnimationOptionAllowUserInteraction animations:animationBlock completion:^ (BOOL finished) {
NSLog(@"Completed");
}];
}
#pragma mark - Touch interaction
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//NSLog(@"Touches began");
[_delegate ingredientTouched];
touchStart = [[touches anyObject] locationInView:self];
NSLog(@"Touched");
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"Touches moved");
CGPoint point = [[touches anyObject] locationInView:self];
self.center = CGPointMake(self.center.x + point.x - touchStart.x, self.center.y + point.y - touchStart.y);
}
@end
这就是我在视图控制器中所做的:
ingredient = [[NKIngredient alloc] initWithFrame:CGRectMake(20, -50, 34, 45)];
[ingredient setImage:[UIImage imageNamed:@"liv1_Burro.png"]];
[ingredient setUserInteractionEnabled:YES];
[[self view] addSubview:ingredient];
[ingredient animate:^ (void) {
[ingredient setFrame:CGRectMake(20, 200, 34, 45)];
}];
即使对象正在动画,一些解决方案也能获得触摸?因为当它NKIngredient
是静止的时,这些touchesBegan/Moved/Ended
方法有效。