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

时间:2021-08-19 23:32:23

http://blog.sina.com.cn/s/blog_74bf41030100xdte.html

问题描述:

         在显示一些类似于模态对话框的窗口时,我们可能需要屏蔽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
{
     
       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;
}