cocos2d lua 實現按鈕長按功能

cocos2d自己並無提供按鈕長按事件的監聽接口,這裏只有本身去實現相似的需求。話很少說,直接上代碼:ui

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
相關文章
相關標籤/搜索