I cant add multiple button instantiations. It shows only the last one. There is supposed to be 4 buttons, but there is only one. This code works with textures but not with Button. Am I missing something?
local label = TextField.new(nil, "Clicked 0 time(s)")
label:setPosition(120, 480)
stage:addChild(label)
-- create the up and down sprites for the button
texUp = Texture.new("button_up_small.png")
up = Bitmap.new(texUp)
texDown = Texture.new("button_down_small.png")
down = Bitmap.new(texDown)
-- create the buttons
posx = 5
posy = 5
cellHeight = texUp:getHeight()
cellWidth = texUp:getWidth()
for i = 1, 2 do
for j = 1, 2 do
button = Button.new(up, down)
button:setPosition(posx, posy)
posx = posx + cellWidth + 5
-- register to "click" event
local click = 0
button:addEventListener("click",
function()
click = click + 1
label:setText("Clicked " .. click .. " time(s)")
end)
stage:addChild(button)
end
posy = posy + cellHeight + 5
posx = 5
end
Comments
posx = 5
posy = 5
cellHeight = texUp:getHeight()
cellWidth = texUp:getWidth()
button={}
for i = 1,4 do
button[i] = Button.new(up, down)
button[i]:setPosition(posx, posy)
posx = posx + cellWidth + 5
-- register to "click" event
local click = 0
button[i]:addEventListener("click",
function()
click = click + 1
label:setText("Clicked " .. click .. " time(s)")
end)
stage:addChild(button)
end
posy = posy + cellHeight + 5
posx = 5
end
stage:addChild(button) -- here it should be button[i], i guess
The code in your reply has compile errors. Thank you though. I guess there is something wrong with the Button object.
up = Bitmap.new(texUp)
down = Bitmap.new(texDown)
out side of the for loops and then you are adding it to 4 different parents [in our case Button.new()] and because of this all the problems occured as any sprite should have only one parent when you try to add it to different parent it will first removed from the previous parent and then adding in new parent
i hope it will help
Likes: rodri