cocos2d lua 实现按钮长按功能

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

 

转载于:https://my.oschina.net/u/223340/blog/889440

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值