I’m trying to implement a button to insert some text into a textbox.
I’ve been trying to use events to call a function on a textbox when the button is pressed.
In the following code, the call to the event does nothing. If I move the call outside of the handleButtonEvent it gets called.
Why won’t the dispatchEvent call work inside of this function?
I think I need to use the event on the textbox to get the current cursor position to enter the text I want to add. For example, let’s say I’m editing the textBox and I want to hit a button to enter the “foo”. I’m trying to invoke the event on the textbox manually so I can do the string insertion.
Maybe there’s another way to do it?
function scene:createScene( event ) local group = self.view -- create a white background to fill screen local bg = display.newRect( 0, 0, display.contentWidth, display.contentHeight ) bg:setFillColor( 0 ) -- black local function inputListener( event ) print ("event name = " .. event.name) if event.type == "myEvent" then print ( "insert string" ) -- print( "start position = " .. event.startPosition ) end end local textBox = native.newTextBox( 200, 200, 280, 140 ) textBox.text = "This is line 1.\nAnd this is line2" textBox.isEditable = true textBox:addEventListener( "userInput", inputListener ) textBox:addEventListener("myEvent", inputListener) local event = { name="myEvent", target=textBox } textBox:dispatchEvent (event) -- this one works, but it's outside of the button event handler -- Function to handle button events local function handleButtonEvent( event ) if ( "ended" == event.phase ) then print( "Button was pressed and released" ) textBox:dispatchEvent (event) -- doesn't work here end end -- Create the widget local button1 = widget.newButton { left = 100, top = 100, id = "button1", label = "Default", onEvent = handleButtonEvent } -- all objects must be added to group (e.g. self.view) group:insert( bg ) group:insert ( button1 ) group:insert ( textBox ) end