Touch handled by two layers

家住魔仙堡 提交于 2019-12-11 04:19:40

问题


I have a CCLayer containing a number of other CCLayers (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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!