Simulating Touch

Hi!
I have a working checkbox which activates a function when touched. I was wondering how I would simulate touching the checkbox in the code. I have read a similar topic: Simulating touching screen but I’m not a very experienced programmer and don’t really understand it. If anyone could elaborate and give a bit more of a simple explanation on this topic it would be greatly appreciated.
Here is my code if it helps:

local function musicBtnPressed( event )
local switch = event.target
print( “Sound is on:”…tostring(switch.isOn) )
end

local options = {
width = 100,
height = 100,
numFrames = 2,
sheetContentWidth = 200,
sheetContentHeight = 100
}
local musicButtonSheet = graphics.newImageSheet( “onOffMusic.png”, options )

    -- Create a group for the music button
    local musicGroup = display.newGroup()

    -- Create music button
    local musicButton = widget.newSwitch(
        {
            left = 70,
            top = 1870,
            style = "checkbox",
            id = "MusicButton",
            width = 200,
            height = 150,
            initialSwitchState = true,
            onPress = musicBtnPressed,
            sheet = musicButtonSheet,
            frameOff = 1,
            frameOn = 2
        }
    )
    musicGroup:insert(musicButton)
    sceneGroup:insert(musicButton)

To make everything clear, can you put together a sample project including the assets to make this work and upload it here?

It doesn’t really make sense to me to simulate a checkbox touch event, and I don’t think it’s even possible to do that. I guess what you’re really looking for is to trigger the same functionality as when someone presses the checkbox. If that’s the case then you can do one or both of the following, depending on your specific needs:

  • Call musicButton:setState() to toggle the switch visually without tapping it. See: https://docs.coronalabs.com/api/type/SwitchWidget/setState.html

  • Call the musicBtnPressed(event) function when you need to. It’s no different from any other function. Just set event.target.isOn to true/false depending on which switch state you want to emulate.

1 Like

While putting together a sample project I found a really easy work around by using buttons instead of a checklist which I’m slightly frustrated about because I was puzzled for quite a while yesterday (oops haha). I guess I won’t need anymore help but thank you very much because you indirectly just solved my issue.

1 Like