The Corona Labs Blog
Posted on . Written by

NOTE: This tutorial has been updated as of February 25, 2013 to reflect the changes in the new Widgets 2.0 library.


The Widgets 2.0 library is now available to users with access to Daily Builds (Build 1034 and beyond). All new widgets share a common trait: each has been written atop a new foundation that is more flexible and stable.

In this tutorial, we’re going to learn about these two widgets:

  • switch — in the form of a radio button, checkbox, or “on/off” slider.
  • segmented control — a “segmented button” in which each segment responds individually.

Important!

Please refer to the current Daily Build documentation as you experiment with new widgets. Several things have been changed or renamed from the old widgets, so you should study the documentation carefully. To assist you, we have included a migration guide to help you make the change. From the linked API page, scroll down to the widget.* section. You’ll find the updated references and migration guide there.

Getting Started

As with several other Corona libraries, you must “require” the widget library to use widgets:

local widget = require( "widget" )

Switch

The first new widget we’ll discuss is the switch widget. This widget extends to three varieties: checkbox, radio button, or on/off slider.

Event Listener

For all switches, you’ll need to create a basic listener function to report the user’s action upon each widget. Let’s create a sample listener which we’ll use throughout this section.

local function onSwitchPress( event )
   local switch = event.target
   local response = switch.id.." is on: "..tostring( switch.isOn )
   print( response )
end

The state of a switch is referenced by the .isOn parameter. At any time, you can read the state of a switch by accessing this property. Its value is true for on/selected or false for off/deselected. You can also set the state of any switch programmatically — see Controlling Switches below.

Checkbox

To create a checkbox switch widget, you may use the following sample:

local checkbox = widget.newSwitch
{
   left = 60,
   top = 230,
   style = "checkbox",
   id = "My checkbox widget",
   initialSwitchState = false,
   onPress = onSwitchPress
}

--Text to show the on/off switch state
checkbox.text = display.newText( tostring( checkbox.isOn ), 0, 0, native.systemFontBold, 18 )
checkbox.text.x = checkbox.x
checkbox.text.y = checkbox.y - checkbox.text.contentHeight

As you can see, the actual widget is created using the widget.newSwitch command with an accompanying “options” table containing, in this example, the following properties, separated by commas:

  • left and top (optional) — the left and top position of the switch. You can also position the switch normally by setting its x and y position afterward.
  • style (required) — for this example, set it to checkbox.
  • id (optional) — this property allows you to set a named reference for the widget. This is useful if you want to use the same event listener function for several switches and identify a specific one by its .id property within the listener function.
  • initialSwitchState (optional) — true = on/selected; false = off/deselected.  Default is false.
  • onPress (optional) — listener function called when the switch is touched.

Radio Button

The radio button switch is created almost exactly the same as the checkbox widget — just set the style parameter to radio. You can copy and paste the same listener function from above to test the on-off functionality of this radio button.

local radioButton = widget.newSwitch
{
   left = 150,
   top = 230,
   style = "radio",
   id = "My radio button widget",
   initialSwitchState = false,
   onPress = onSwitchPress
}

--Text to show the on/off switch state
radioButton.text = display.newText( tostring( radioButton.isOn ), 0, 0, native.systemFontBold, 18 )
radioButton.text.x = radioButton.x
radioButton.text.y = radioButton.y - radioButton.text.contentHeight

On/Off Switch

The on/off switch is a small flick/tap switch which is generally animated on change. This is the default appearance for a switch widget. The setup is similar to the other switch widgets with a few key differences.

local onOffSwitch = widget.newSwitch
{
   left = 250,
   top = 230,
   id = "My on/off switch widget",
   initialSwitchState = true,
   onRelease = onSwitchPress
}

The main difference is that the event listener function is specified by the onRelease parameter, not the onPress parameter. In this case, the “release” event occurs when the touch is released and the switch motion stops at a resting position, either on or off.

Controlling Switches

The new switch widgets allow you to programmatically control their state. Just use the switch:setState() command and pass the following parameters inside a table:

switch:setState{ isOn = true, isAnimated = true, onComplete = function }
  • isOn (required) — sets the switch to on or off.
  • isAnimated (optional) — true = animate the state change; false = change with no animation. Applies only to On/Off switches.
  • onComplete (optional) — listener function called when the switch is changed.

Segmented Control

The segmented control allows you to easily create a multi-segment button in which each segment responds to the users touch in an “on/off” state and returns the values associated with it.

Event Listener

As with the switch widget, you’ll need to create a basic listener function to report the user’s action upon the segmented control.

local function onControlPress( event )
   local target = event.target
   print( "Segment Label is:", target.segmentLabel )
   print( "Segment Number is:", target.segmentNumber )
end

The segmented control sends two essential values to the listener: the segment label and segment number of the segment you touched.

Basic Segmented Control

Creating the control itself is simple. Look at the following example:

local segmentedControl = widget.newSegmentedControl
{
   left = 65,
   top = 110,
   segments = { "s1", "s2", "s3", "s4" },
   segmentWidth = 50,
   defaultSegment = 4,
   onPress = onControlPress
}
  • left and top (optional) — the left and top position of the control. You can also position the control normally by setting its x and y position afterward.
  • segments (required) — sub-table in which you define the segments; it determines the total count and the label that appears on each. Simply define them as comma-separated strings.
  • segmentWidth (optional) — the pixel width of each segment. Default is 50 pixels.
  • defaultSegment (optional) — this property allows you to set the segment that is “on” when the control is rendered. Specify a number between 1 and the total number of segments. If you don’t specify this property, it defaults to the first segment.
  • onPress (optional) — listener function called when the control is touched.

More Widgets…

That’s it for Part 1, but please proceed to New Widgets: Part 2 to learn about the button, tab bar, slider, stepper, and spinner.

23 Responses to “New Widgets: Part 1”

  1. J. A. Whye

    You said, “As for the previous widgets, these will eventually be totally rewritten atop the new foundation.”

    Can you give us a clue as to whether the changes will be just “under the hood” or will we have to make code changes as well to use the improved existing widgets?

    Jay

    Reply
    • Brent Sorrentino

      Hello Jay,
      The new widgets (to replace the existing ones) will be given as much attention as possible in regards to making the “transition” painless. Some changes you can expect will be the implementation of image sheets for the widget assets (instead of individual images), which is all part of improving performance in general. However, the “theme” files for the widgets will remain essentially the same.

      Of course, there are probably a few things which will need to be changed in your code after the transition, but I expect it will occur only when necessary… and the final result (like the switch from the old sprite library to the new one) will be a faster, more user-friendly library.

      Reply
  2. Marco

    Great news! It’s about time the widgets got some love.

    Now, who of the IDE developers will be the first to offer a drag & drop UI design tool?

    Reply
    • Peter

      A while back Corona itself gave us a preview of a “level builder,” which is what I imagine the UI drag and drop tool to be. Any ETA on when we might be hearing about that again?

      Reply
      • David

        corona has given so much promises earlier and they had simply left them it’s common here better if you do not take any thing on the roadmap seriously as there is very very very low chance that they will finish it

        Reply
  3. Mark

    Is there a way yet to toggle the state of a switch programmatically? I was hoping isOn would do the trick, but I couldn’t see anything that worked. Thanks!

    Reply
    • Brent Sorrentino

      Hi Mark,
      Very good question. I’ve been in discussion with Corona about this, and the agreement is that it should happen sooner than later, so I’ll be urging sooner. :)

      The issue is the “method” in which to affect a widget programmatically… my initial thoughts were to use the “object:dispatchEvent()” API, but this becomes really confusing when applied to different widgets… what event do you “dispatch” in each case? Does the dispatch have a “phase” or not? And so forth…

      The feeling that I’m getting is that a method will be implemented on a per-widget basic, when necessary for that widget. A switch obviously needs a convenient method to just turn it on or off, while the revamped “picker wheel” (when it’s done) might need a way to programmatically jump to a specific row within a specific column.

      If you have any other ideas, please suggest it here, as I’m monitoring this thread closely and will pass on thoughts and ideas to Corona. Thanks!

      Reply
      • Mark

        Well I definitely don’t know the best way to do it behind the scenes. From my experience with Qt, almost all buttons inherit a setChecked(bool) method that is very handy, and then you can usually listen for a change to the check state if you need to.

        My current use case, I’d like to validate some stuff to confirm if a user can even turn the switch on as soon as they touch it, before it changes from off to on. If the validation fails, I’ve got a dialog that pops up. If it succeeds, it should turn on. The only problem is right now I don’t think I can block the switch actually turning on, or turn it off again in the code (if any of that makes sense). I had programmed my own switch turning on/off that didn’t have the nice slide transitions, but I was hoping to try this out.

        Reply
  4. Mitaten

    Great tutorial and great news about the upcoming widgets!! Our current apps are all heavily depended on the widgets library so this is great news, thanks!

    Reply
  5. Simeon

    The radio buttons are worthless without being able toggle the others off when one is selected. It’s nice to have widget improvements though, but we need to be able to do that. If there is a known solution, I’d love to hear about it. Haven’t found anything yet. :(

    Reply
    • Brent Sorrentino

      Hello Simeon,
      This is a known issue and we’re aware of it. I am working along with the widgets engineer to help push some of these features in to the new widgets a.s.a.p. I can’t give you an exact ETA, just say that it’s been clearly noted on the “to do” list.

      Reply
  6. Frank

    Dear Brent,

    how does the roadmap for widgets look like. Especially, what is the ETA on a textfield widget that works in the Windows Corona Simulator ?

    This information would help us to decide whether to work on a widget ourselves, our wait for the widget from CoronaLabs and not waste our time on a widget that is available from CL anyhow.

    Your feedback would be much appreciated
    Best regards
    Frank

    Reply
    • Brent Sorrentino

      Hello Frank,
      Thanks for your detailed questions. I’ll address them each to the best of my knowledge, including that from the second post you wrote:

      While the widgets were admittedly delayed, the new set should roll out very soon; in fact, I started writing the next tutorial today. These tutorials will likely roll out in a series following this one you responded to (Part I).

      Text field in Windows Simulator… I’m not sure if this is what you mean, but there will be a Search Field widget as part of the new set, which allows you to type (whatever) into a textfield-looking box. While it’s designed for a “search”, and the default look is geared toward that, the images will be editable to some degree if you’re looking for a more basic “text field”. I have tested the current version and it works in the Mac Simulator, so I assume it will work in the Windows Sim too.

      All of the new widgets will be built on a new, much-improved framework, but I’m not sure if end users will be able to dig deep into this framework to modify low-level behavior. I would suspect the answer is “no”, but I can ask the widget engineers about it. That being said, the new widgets will be far more customizable than the previous ones visually, and eventually I will write a complete tutorial about “skinning” widgets.

      Lastly, in regards to creating your own custom widgets beyond the scope of “normal” widgets, this might need to be done on your side, depending on your needs. After the initial rollout, the plan is to add new widgets as they seem necessary and useful, and when I have more specific details I can provide them.

      Hope this helps, if you have any other questions don’t hesitate to ask.
      Best regards,
      Brent

      Reply
      • frank

        Hello Brent, thanks a lot for the quick response . Allow me to come back to you if I have additional questions after you published the second part of your article.

        Best
        Frank

        Reply
  7. frank

    Hi Brent,

    you are saying the new widgets are built on a new framework. Is there any information on this framework available, so that custom widgets can be built on top of this framework ?

    Thanks in advance
    Frank

    Reply
  8. Steve Taylor

    Where do I find the current widget_iosfile and assets? The dropbox shown above is no longer active. Thanks much!!!

    Reply
    • Brent Sorrentino

      Hi Steve,
      I restored the download link; sorry for the inconvenience. When the next batch of Widgets are released, these files will be bundled in with the build. In the meantime, however, you can use the updated path. Thank you.

      Reply
      • frank

        Brent, when are the widgets ready ? Is a beta available ? Is the source code for the widgets available ? Thanks, Frank

        Reply
  9. vicky.gn

    Hi Brent,
    I am now using the trial version 2012.971 and the os is winxp ,the app build for android.
    Can the new widgets be available for me now ?
    Thanks~~~

    Reply
  10. David Rangel

    Vicky.gn – Unfortunately the new widgets will not be available for trial users until we release our next public build. We are currently setting a date for that, but it is at least 3-4 weeks away.

    David

    Reply
  11. Renato - RBG

    In the On/Off Switch, the description says that “he event listener function is specified by the onRelease parameter, not the onPress parameter” but I tested here and found the opposite, the onRelease listener does not work and the onPress does.

    Reply

Leave a Reply

  • (Will Not Be Published)