问题
I have a CCLayer
containing a number of other CCLayer
s (like items of text etc). I have another CCLayer
to the left hand side with which I want to display thumbnails of a number of these 'scenes'.
The left hand CCScrollLayer
should respond to touches which are within its bounds, while elements in the right hand layer should respond to touches inside their individual bounds.
The problem I'm seeing is that when I drag for example a layer on the right, the CCScrollLayer
to the left is responding and scrolling. The elements on the right are unaffected, when I scroll the scroll layer though. It's as though the CCScrollLayer
's bounds are too big, which they're not because I've even set them purposely to 100 pixels wide. Is there an unexplained behaviour at work here?
The effect can be seen at http://imageshack.us/photo/my-images/210/dragd.png/
回答1:
By default, CCLayer is register as standard touch delegate. You must register it as targeted delegate. In this case CCLayer can claim touch and other touchable elements will not receive it. You can do it by overriding CCLayer method
-(void) registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority: self.priority swallowsTouches:YES];
}
after this you must replace your delegate methods with these ones
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
@optional
// touch updates:
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;
your ccTouchBegan:withEvent:
method should be like this
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
BOOL shouldClaimTouch = NO;
BOOL layerContainsPoint = // check if current layer contains UITouch position
if( layerContainsPoint )
{
shouldClaimTouch = YES;
}
// do anything you want
return shouldClaimTouch;
}
just don't forget to convert touch's UI coordinates to GL. If this method returns YES, this touch will not be received by any other layer.
回答2:
Thanks @Morion, that was it. My detection method looks like this.
StoryElementLayer *newLayer = nil;
for (StoryElementLayer *elementLayer in self.children) {
if (CGRectContainsPoint(elementLayer.boundingBox, touchLocation)) {
newLayer = elementLayer;
break;
}
}
来源:https://stackoverflow.com/questions/11056222/touch-handled-by-two-layers