且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[cocos2d]如何实现模态对话框

更新时间:2021-12-29 22:28:08

问题描述:
     在显示一些类似于模态对话框的窗口时,我们可能需要屏蔽touch事件,不让在弹出框下面的界面响应touch事件。

     而弹出框上某些区域,或者按钮可以响应touch事件。

解决方案:

      1> 给弹出框添加带吞噬能力的touch代理功能。

[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:kCCMenuTouchPriority + 1 swallowsTouches:YES];

     

注意:
     a>:代理是会被retain的。所以使用完后务必要移出。
[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
     b>:priority其值越小,越是会优先响应touch事件。
               这里使用kCCMenuTouchPriority + 1 既该界面的响应优先级比菜单按钮优先级低。如果你希望又最高的优先级***使用INT32_MIN+1

     2> 实现代理方法ccTouchBegan:返回YES表示吞噬touch事件,则其他代理都不收到该事件了。
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    /**override to what you like*/
    return YES;
}
     如果需要在某个区域内可以响应touch事件,则可以添加如下代码
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
     CGRect aRect = CGRectMake(50, 50, 50, 50);
    CGPoint touchpoint = [touch locationInView:[touch view]];
    touchpoint = [[CCDirectorsharedDirector] convertToGL: touchpoint];
    return !CGRectContainsPoint(aRect, touchpoint);
}
     如果你希望除了菜单按钮以外的区域都不响应touch事件你也可以这样写:
  - (BOOL)ccTouchBegan:(UITouch *)touch 
  withEvent:(UIEvent *)event
{
CCMenu *menu = 
(CCMenu *)[selfgetChildByTag:kMenuItemLayerTag];
if ([menu itemForTouch:touch])
{
returnNO;
}
    
returnYES;
}
     注意:其中itemForTouch:方法的使用有点技巧,提示这个方法是ccmenu的私有方法

     当然除了使用这种暴力方式以外,也可以用优先级来实现,如上面提到的priority:kCCMenuTouchPriority + 1。这种方式就需要大家能良好的执行约定。同时用优先级来控制有个问题,如果与下层的按钮重叠的时候,是那个执行那?