解决CCScrollView中菜单条目在不可见时仍响应点击事件的问题

本文介绍了一种使用Lua语言实现ScrollView中不可用菜单项点击响应的方法。具体步骤包括禁用菜单项事件并记录到集合中,重写touchBegan和touchEnded方法来捕捉触摸事件,最后通过手动点击事件派发实现特定菜单项的选择。


解决思路

1. 在添加菜单条目到ScrollView的时候通过setEnable方法关闭菜单条目的事件响应,并添加到一个集合中(items)

2. 重写CCLayer的touchBegan、touchEnded方法

3. 在touchBegan方法里记录触摸点(beganPoint),然后在touchEnded方法里判断(如果触摸点在ScrollView中 && beganPoint == touchPoint(点击事件判断) )

    判断成立,则迭代items,如果触摸点在item的范围则调用item的selected()方法

    


示例代码


lua代码:添加Item

</pre><pre>

-- 添加菜单条目
function addItem(self, itemId)
	-- 创建菜单条目
	local item = CCMenuItemImage:create("res/ui/shop/shop_05.png","res/ui/shop/shop_04.png")
	-- 设置菜单条目不可用
	item:setEnabled(false)
	self.menu:addChild(item)
	-- 添加菜单条目到集合
	table.insert(self.items,item)
end


lua代码:重写touchBegan和touchEnded方法


function touchBegan(self, _touchX, _touchY, _preTouchX, _preTouchY)
    -- 坐标点转换
    local touchPoint = self.node_:convertToNodeSpace(ccp(_touchX, _touchY))
    -- 判断触摸点是否在ScrollView上
    if self.svItems:boundingBox():containsPoint(touchPoint) then
        -- 标记触摸点在ScrollView
        self.touchSv = true
    else
        self.touchSv = false
    end
    self.beganPoint = touchPoint
    return true
end


function touchEnded(self, _touchX, _touchY, _preTouchX, _preTouchY)
    -- 坐标点转换
    local touchPoint = self.node_:convertToNodeSpace(ccp(_touchX, _touchY))
    -- 当触摸点在ScrollView上,并且手指按下时的点与手指离开时的点相同时,判断是否点击了ScrollView上的条目
    if self.touchSv and self.beganPoint.x == touchPoint.x then
        self:selectItemByPoint(touchPoint)
    end
end

lua代码:手动点击事件派发

</pre><pre>
function selectItemByPoint(self, touchPoint)
        -- 坐标点转换
        local point = self.scrollView:getContainer():convertToNodeSpace(touchPoint) 
        for id,item in pairs(self.items) do
            -- 默认设置条目为未选中
            item:unselected()
            -- 判断触摸点是否在当前菜单条目上
            if item:boundingBox():containsPoint(point) then 
                cclog("selected item" .. id)
                -- 选中该菜单条目
                item:selected() 
            end 
        end
end



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值