如何动态创建对象(来自本机库的文本字段),并向它们添加事件

How to create dynamically objects (textFields from native library), and add event to them

我已经使用 corona 动态创建了 textField,但是我无法向这些对象添加事件,因为我需要将 textField 的信息存储在 table.

我以前在 c# 中只使用一个事件来执行此操作,我要求获得文本框的焦点,但在这种情况下我不知道该怎么做。 属性 textField 的焦点不存在(您可以设置焦点,但不能请求状态)。

另一方面,我尝试创建一个带有函数的 table,并将这些函数传递给 textField 的 addEventListener,但它不起作用。

如果有任何解决此问题的建议,我将不胜感激,谢谢!!!!

local widget=require("widget")
local native=require("native")
local listTextFields={}

local positionY=display.contentCenterY

--Handle for any textField

local function textFieldHandle( event )

if ( event.phase == "began" ) then


elseif ( event.phase == "ended" or event.phase == "submitted" ) then

    --???

elseif ( event.phase == "editing" ) then

    --???
end

end

--this is the button's event
local function buttonEvent_1 (event)

listTextFields[#listTextField+1]=native.newTextField{
x=display.contentCenterX,
y=positionY,
width=100,
height=50
} 
positionY=positionY+70

--This is the main problem


lisTextFields[#listTextFields]:addEventListener("userInput",textFieldHandle)

--But in this case I don't now how to build the handle for the textField,  cause I don't now what textField have the focus.
end


-- Button
local propertiesButton = 
{
left = display.contentCenterX,
top = display.contentCenterY - display.contentHeight/2,
width = 80,
height = 80 ,
label= "Add",
defaultFile = "defaultButton.png",
overFile = "overButton.png",
onPress=buttonEvent_1

}
button1 = widget.newButton(propertiesButton)

The property focus for the textField doesn't exist (you can set the focus, but you can't ask for the state).

当然可以。 有一种方法可以知道哪个 textField 具有焦点.. 首先让我添加一个 display.newText() 用于测试..所以在你的 eventHandlers

之前的顶部
local test = display.newText( " ", 100, 100, nil, 20 )

现在为每个 textField 添加一个 id 属性,因此在创建 textField 之后我们添加 ..

listTextFields[#listTextField+1]=native.newTextField{
x=display.contentCenterX,
y=positionY,
width=100,
height=50
} 

listTextFields[#listTextFields].id = #listTextFields

确定哪个 textField 具有焦点..我们可以在 eventHandler 中使用 event.phase == "began" ..我们可以通过 event.target 访问 textField ...所以现在我将显示带有焦点的 textField 的 id ..

local function textFieldHandle( event )
if ( event.phase == "began" ) then
test.text = "The Focus on the textField # " .. event.target.id
end
end