在Corona Lua中处理事件。

我是corona的新手,不知道如何有效地组织我的代码。我正在尝试在用户单击leftHam图像时注册单击事件,但是我不知道如何最有效地实现这一点。现在,我得到了leftHam为nil的错误,虽然在创建时它应该被分配一个值。

local composer = require( "composer" )
local widget = require( "widget" )

local scene = composer.newScene()
local _H = display.contentHeight
local _W = display.contentWidth

leftNavBtn = nil
local navbarGroup

function scene:create( event )

    local sceneGroup = self.view

    local background = display.newImage("res/bg.png" )
        background:scale( _W, _H )
        background.x = _W
        background.y = _H

    local navbarGroup = display.newContainer(_W, _H/4)
         navbarGroup.x = _W /2
        --navbarGroup.y = 0

    local top_bar = display.newImage("res/home/top_bar.png")
        top_bar.y = top_bar.height/2
    navbarGroup:insert(top_bar)

    --local leftNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
        leftNavBtn.y =  leftNavBtn.height/1.5
        leftNavBtn.x = - navbarGroup.width/2 + leftNavBtn.width

    leftNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
        leftNavBtn.y =  leftNavBtn.height/1.5
        leftNavBtn.x = - navbarGroup.width/2 + leftNavBtn.width
    navbarGroup:insert(leftNavBtn)

    local rightNavBtn = display.newImageRect("res/home/hamburger.png", 100, 100)
        rightNavBtn.y =  leftNavBtn.height/1.5
        rightNavBtn.x =  navbarGroup.width/2 - leftNavBtn.width
    navbarGroup:insert(rightNavBtn)

end

function test()
    print("clickedddddddddddd")
end

function leftNavBtn:touch(event)
    if event.phase == "began" then
        display.getCurrentStage( ):setFocus(self)
        self.isFocus = true

    elseif self.isFocus then
        if event.phase == "moved" then
            print("moved")
        elseif event.phase == "ended" or event.phase == "cancelled" then
            display.getCurrentStage( ):setFocus(nil)
            self.isFocus = false

        end
    end
    return true
end

leftNavBtn:addEventListener( "touch", test )
scene:addEventListener( "create", scene )

return scene
点赞
用户258523
用户258523

你是想说leftNavBtn吗?因为leftHam在任何地方都不存在。

scene:create中创建了leftNavBtn,但尝试在任何地方调用该函数之前使用它(leftNavBtn:addEventListener("touch",test))。

scene:create中也在创建它之前使用了leftNavBtn,因为你注释掉了这行local leftNavBtn = display.newImageRect("res/home/hamburger.png",100,100),而没有注释掉它后面的两行(然后你立即复制了这三行)。

2015-02-26 15:11:39