NOTE! You are browsing legacy documentation. For latest visit docs.nativescript.org.

NativeScript Core

Switch

The Switch component allows users to toggle a control between two states. The default state of the component is off, or false, however you can change the state by setting the checked property to a boolean value. To handle the state change event you can use the checkedChange property, which notifies the app when the value has changed.

Usage

<Switch checked="true" loaded="onSwitchLoaded"/>
function onSwitchLoaded(argsloaded) {
    const mySwitch = argsloaded.object;
    mySwitch.on("checkedChange", (args) => {
        const sw = args.object;
        const isChecked = sw.checked;
        console.log(`Switch new value ${isChecked}`);
    });
}
exports.onSwitchLoaded = onSwitchLoaded;
import { Switch } from "tns-core-modules/ui/switch";
export function onSwitchLoaded(argsloaded) {
    const mySwitch: Switch = <Switch> argsloaded.object;
    mySwitch.on("checkedChange", (args) => {
        let sw: Switch = <Switch> args.object;
        let isChecked = sw.checked;
        console.log(`Switch new value ${isChecked}`);
    });
}

Styling

<Switch color="yellow" backgroundColor="green" offBackgroundColor="red"/>

Creating Switch component via Code-Behind

<!-- The Layout that will hold the dynamically created Switch -->
<StackLayout id="stackLayoutId" class="m-15 text-center" width="80%" height="80%">
      <Label text="{{ 'Result: ' + swResult}}" textWrap="true" class="h2"/>
</StackLayout>
// creating new Switch and binding the checked property
const mySwitch = new switchModule.Switch();
const options = {
    sourceProperty: "isChecked",
    targetProperty: "checked"
};
mySwitch.bind(options, vm);
mySwitch.on("checkedChange", (args) => {
    console.log(args.object.checked);
});

// setting up mySwitch.checked to true via binding
vm.set("isChecked", true);

// The above code is equivalent to binding via the XML
/*
    <Switch checked="">
*/

// adding the created element to already existing layout
stackLayout.addChild(mySwitch);
// creating new Switch and binding the checked property
const mySwitch = new Switch();
const options = {
    sourceProperty: "isChecked",
    targetProperty: "checked"
};
mySwitch.bind(options, vm);
mySwitch.on("checkedChange", (swargs) => {
    console.log((<Switch>swargs.object).checked);
});

// setting up mySwitch.checked to true via binding
vm.set("isChecked", true);

// The above code is equivalent to binding via the XML
/*
    <Switch checked="">
*/

// Adding the created element to already existing layout
stackLayout.addChild(mySwitch);

Properties

Name Type Description
checked boolean Gets or sets if a switch is checked or not.
offBackgroundColor Color Gets or sets the off-state color.

API References

Name Type
tns-core-modules/ui/switch Module
Switch Class

Native Component

Android iOS
android.widget.Switch UISwitch