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


解决思路

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



posted on 2014-08-19 15:51  linchaolong  阅读(280)  评论(0编辑  收藏  举报

导航