cocos2d本身并没有提供按钮长按事件的监听接口,这里只有自己去实现类似的需求。话不多说,直接上代码:
local LONG_PRESS_TIME = 3
local PRESS_INTERVAL_TIME = 1
function DemoLongPressBtn:ctor()
self.is_touch = false
self.tick_count= 0
self.long_press= false
self:init_button()
end
function DemoLongPressBtn:init_button()
--按钮也可以是通过ccs生成获取的。
local button = ccui.Button:create()
button:addTouchEventListener(function(sender, eventType)
if eventType == ccui.TouchEventType.began then
self.is_touch = true
local seq = cc.Sequence:create(cc.CallFunc:create(function() self:timer_press() end)
,cc.DelayTime:create(PRESS_INTERVAL_TIME))
self.long_press_action = self:runAction(cc.RepeatForever:create(seq))
return true
elseif eventType == ccui.TouchEventType.ended then
self:stopAction(self.long_press_action)
self.is_touch = false
if self.long_press then
self.long_press = false
self.tick_count = 0
return false
end
if self.tick_count <= 2 then
if self.tick_count == 1 then--点击一次的情况
self:on_click()
else
--TODO介于1s~3s之间的情况
end
self.long_press = false
self.tick_count = 0
return false
end
end
end
function DemoLongPressBtn:on_click()
--点击1次对应的功能逻辑处理
end
function DemoLongPressBtn:timer_press()
if self.is_touch then
self.tick_count = self.tick_count + PRESS_INTERVAL_TIME
if self.tick_count >= LONG_PRESS_TIME then
self:stopAction(self.long_press_action)
self.tick_count= 0
self.long_press= true
self.is_touch = false
end
end
end
return DemoLongPressBtn