我需要显示图像,以便模仿各种"家庭"上的iOS应用图标的布局。页面。我编写了代码来显示各种图像;但是,我无法弄清楚如何在点击事件中返回与每个单独图像相对应的值。
到目前为止,这是我的代码:
plates = {
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png",
"fat-burning-foods.jpg",
"fresh_food.jpg",
"fat-burning-foods.jpg",
"star.png"
}
-- The PlateId will have corosponding indexes with the plates array. It will be used to query plate information
plateId = {1,2,3,4}
plateIdRef = {}
index = 1
platesIsh = {1,2,3,4,5,6,7,8}
local anX = 20
local anY = 120
for i=1, #plates do
local bufferY = 20
if index == 4 then
bufferY = 110
anX = 20
elseif index > 4 then
bufferY = 110
end
if index == 7 then
bufferY = 200
anX = 20
elseif index > 7 then
bufferY = 200
if index == 10 then
bufferY = 290
anX = 20
elseif index > 10 then
bufferY = 290
end
end
local dummyVar = math.random()
dummyVar = display.newImageRect(plates[index],80, 80)
sceneGroup:insert(dummyVar)
dummyVar.x = anX + 30
dummyVar.y = anY + bufferY
table.insert(plateIdRef, index)
function dummyVar:touch( event )
if event.phase == "began" then
local alert = native.showAlert( "Corona", event.target, { "OK", "Learn More" } )
--print( "You touched "..dummyVar)
return true
end
end
dummyVar:addEventListener( "touch", dummyVar )
anX = anX + 110
index = index + 1
end
有什么想法吗?
答案 0 :(得分:1)
好的,看看它是如何工作的一个例子:
local plates = {}
local function plateTouch( self, event )
local phase = event.phase
if phase == "ended" then
print( "You touched ".. self.id)
end
return true
end
for i=1, 3 do
plates[i] = display.newImageRect("test.png",80, 80)
plates[i].id = "plate " .. i
plates[i].x = 90 * i
plates[i].y = 90
plates[i].touch = plateTouch
plates[i]:addEventListener( "touch", plates[i] )
end
创建每个印版时,您可以定义id
属性以了解按下了哪个按钮,也可以添加所需的任何其他属性。
您可以看到API docs for touch event并查看带有表侦听器的示例。
其他方法可能是面向对象的解决方案,您可以在其中定义一个类来创建新版块,但可能首先您需要了解该示例。