setFocus() does not work

Why is there no focus on the second rectangle?

-- Create two display objects on the screen local newRect1 = display.newRect( display.contentCenterX, 160, 60, 60 ) newRect1:setFillColor( 1, 0, 0.3 ) local newRect2 = display.newRect( display.contentCenterX, 320, 60, 60 ) newRect2:setFillColor( 0.3, 0, 1 ) -- Touch event listener local function touchListener( event ) print("logging") end -- Add a touch listener to each object newRect1:addEventListener( "touch", touchListener ) newRect2:addEventListener( "touch", touchListener ) display.getCurrentStage():setFocus( newRect2)

You have just misunderstood what focus means, because the focus is on newRect2.

-- Create two display objects on the screen local newRect1 = display.newRect( display.contentCenterX, 160, 60, 60 ) newRect1:setFillColor( 1, 0, 0.3 ) newRect1.id = "newRect1" local newRect2 = display.newRect( display.contentCenterX, 320, 60, 60 ) newRect2:setFillColor( 0.3, 0, 1 ) newRect2.id = "newRect2" -- Touch event listener local function touchListener( event ) print( event.target.id ) end -- Add a touch listener to each object newRect1:addEventListener( "touch", touchListener ) newRect2:addEventListener( "touch", touchListener ) display.getCurrentStage():setFocus( newRect2)

Anywhere you press, the function will print out “newRect2”, this is because you’ve set focus to it, i.e. every touch event goes to it regardless of where you touch on the screen.

You have just misunderstood what focus means, because the focus is on newRect2.

-- Create two display objects on the screen local newRect1 = display.newRect( display.contentCenterX, 160, 60, 60 ) newRect1:setFillColor( 1, 0, 0.3 ) newRect1.id = "newRect1" local newRect2 = display.newRect( display.contentCenterX, 320, 60, 60 ) newRect2:setFillColor( 0.3, 0, 1 ) newRect2.id = "newRect2" -- Touch event listener local function touchListener( event ) print( event.target.id ) end -- Add a touch listener to each object newRect1:addEventListener( "touch", touchListener ) newRect2:addEventListener( "touch", touchListener ) display.getCurrentStage():setFocus( newRect2)

Anywhere you press, the function will print out “newRect2”, this is because you’ve set focus to it, i.e. every touch event goes to it regardless of where you touch on the screen.