問題是這樣的:我有NKIngredient
這是UIImageView
的一個子類。我已經在其中實施了touchesBegan/Moved/Ended
方法,並在YES
上設置了userInteractionEnabled
。但主要問題是,當我在視圖控制器中動畫我的NKIngredient
實例時,我需要在動畫期間可以觸摸該對象。這是不可能的! 的NKIngredient
接口:UIViewAnimationOptionAllowUserInteraction不起作用
@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
方法的作品。
這是什麼版本的iOS上運行? –
你可以嘗試UIGestureRecognizer類。 –
我正在使用iOS 6. UIGestureRecognizer是一個很好的解決方案,但我需要移動該對象。所以,用戶可以拖動對象。是否可以使用UIGestureRecognizer? @Ishank –