本文地址:
http://www.cppblog.com/zdhsoft/archive/2016/04/12/213238.htmlcocos2dx笔记汇总用cococstudio编辑的UI,都是带Touch事件的,这样,使得我们编写UI逻辑处理简单很多了,这个是基于lua实现,不需要改cocos2dx引擎.
1 --判断是否是有效的事件类型
2 function isValidTouchEventType(paramEventType)
3 if paramEventType == TOUCH_EVENT_ENDED or paramEventType == TOUCH_EVENT_BEGAN or paramEventType == TOUCH_EVENT_MOVED or paramEventType == TOUCH_EVENT_CANCELED then
4 return true
5 else
6 return false
7 end
8 end
9 --根据Widget的tag来侦听
10 function AddListenerByTag(paramWidget, paramTag, paramEventType, paramCallBack)
11 if not paramWidget then
12 cclog("参数paramWidget为nil对象")
13 return
14 end
15 if not ui.isValidTouchEventType(paramEventType) then
16 cclog("未知的事件类型:"..paramEventType)
17 return
18 end
19
20 local st = ui.getWidgetByTag(paramWidget, paramTag)
21 if not st then
22 return
23 end
24
25 local function OnTouch(paramSender, paramType)
26 if paramType == paramEventType then
27 paramCallBack(paramSender, paramType)
28 end
29 end
30 st:addTouchEventListener(OnTouch)
31 end
32
33 --根据Widget的Name来侦听
34 function AddListenerByName(paramWidget, paramWidgetName, paramEventType, paramCallBack)
35 if not paramWidget then
36 cclog("参数paramWidget为nil对象")
37 return
38 end
39 if not ui.isValidTouchEventType(paramEventType) then
40 cclog("未知的事件类型:"..paramEventType)
41 return
42 end
43
44 local st = ui.getWidgetByName(paramWidget, paramWidgetName)
45 if not st then
46 return
47 end
48
49 local function OnTouch(paramSender, paramType)
50 if paramType == paramEventType then
51 paramCallBack(paramSender, paramType)
52 end
53 end
54 st:addTouchEventListener(OnTouch)
55 end
使用实例:
1 local stTopInfoItem = GUIReader:shareReader():widgetFromJsonFile("ui/top_info.json")
2 ui.AddListenerByTag(stTopInfoItem, TAG.TOP_RET, TOUCH_EVENT_ENDED, PlaceRandomLayer.OnReturnMain)