Important note
This is a community project
Svelte Native is developed by members of the Svelte community who wish to have the same smooth development experience on mobile devices as they have on the web. This project is not an officially supported product of either the NativeScript or Svelte projects.
Yet.
Introduction
What is NativeScript?
NativeScript is an open-source framework to develop apps on the Apple iOS and Android platforms. It is open source and can be found on github.
What is Svelte?
Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.
Instead of using techniques like virtual DOM diffing, Svelte writes code that surgically updates the DOM when the state of your app changes.
What is Svelte Native
Svelte Native is a tool for building mobile applications. It combines NativeScript's access to the native platform views and Svelte's fast and efficient view updates to allow you to build native mobile experiences using tools such as HTML, CSS and Javascript.
Getting Started
Quick Start
Install Nativescript
Svelte-Native works on top of NativeScript. To install NativeScript:
$ npm install -g nativescript
Check it worked by running ns
:
Install the NativeScript Playground app
Svelte-Native really is native, so it needs a mobile device to run. The build setup for iOS or Android can be a pain, so the wizards at Nativescript have created the NativeScript playground app. This allows us to run Svelte-Native application code without having to build the full mobile application.
Create a new Svelte-Native app
The easiest way to get started is to use the latest template app:
$ ns create myapp --svelte
A fresh svelte-native app will be found in the myapp
folder.
Launch It
Launch your app with:
$ cd myapp
$ ns preview
You will need to scan the QR Code using the "Playground" app you installed previously.
Advanced Install
To compile your apps for distribution, you will need to set up your system for local compilation.
Svelte-Native runs on top of an unmodified NativeScript platform. Installation instructions for your operating system can be found in the Native Script Guide.
Check you have the NativeScript build environment configured correctly by using the Nativescript doctor command:
$ ns doctor
Once that is happy you can do a full compile and launch of your application with
$ ns run android
or
$ ns run ios
Using Nativescript Plugins
Since Svelte Native uses unmodified NativeScript, it is possible to use NativeScript plugins, such as those found on the marketplace.
Follow the instructions for the component and if there isn't instructions for svelte, look for the Nativescript Vue instructions involving registerElement
.
Register the element using registerNativeViewElement(tagName, ()=> NativeConstructor)
eg for Nativescript Mapbox Plugin
$ ns plugin add nativescript-mapbox
in app.ts before app startup
import { registerNativeViewElement } from 'svelte-native/dom'
registerNativeViewElement("mapBox", () => require("nativescript-mapbox").MapboxView);
You can now use the <mapBox>
tag in your application following the plugin's documentation.
NOTE For examples of how to register more complex components, check out the code in svelte-native-nativescript-ui which supports the Nativescript Professional UI components
Navigation/Routing
Since Svelte Native is a thin bridge between Svelte and NativeScript. It is best if you familiarize yourself with the core concept of routing in NativeScript.
Routing in Svelte Native is designed to be very similar and the svelte-native
module exposes the following functions:
navigate
Specify the destination page with the mandatory page
option. This takes a Svelte
component class.
<page>
<actionBar title="Master" />
<stackLayout>
<button text="To Details directly" on:tap="{ () => navigate({ page: Detail }) }" />
</stackLayout>
</page>
<script>
import Detail from './Detail.svelte'
import { navigate } from 'svelte-native'
</script>
Passing props to the target component
You can specify the props used to create the Svelte component using the props
option.
<page>
<actionBar title="Master" />
<stackLayout>
<button text="To Details directly" on:tap="{showDetailWithProps}" />
</stackLayout>
</page>
<script>
import Detail from './Detail.svelte'
import { navigate } from 'svelte-native'
function showDetailWithProps() {
navigate({
page: Detail,
props: { message: "Hello from master" }
})
}
</script>
Specifying a Frame
Each <frame>
element has its own navigation stack. If you are using multiple frames, you may want to specify in which frame the navigation will occur. For example, having a button in the sidebar that changes the page in the main area. You can do this by adding the frame
option:
navigate({
page: Detail,
frame: '<id, or ref, or instance>'
})
The value for the frame
option can be one of the following:
- the
id
of the<frame>
component (for example:<frame id="main-frame">
) - a reference to the
<frame>
(for example:<frame bind:this="{mainFrame}">
) - a NativeScript
Frame
instance.
If no frame is specified, the navigation will occur on the topmost frame.
Other Options
For more information about the options that you can pass, see NavigationEntry.
goBack
To navigate back to a previous page, use the goBack
function.
<page>
<actionBar title="Detail"/>
<stackLayout>
<button text="Back to Master" on:tap="{goBack}" />
</stackLayout>
</page>
<script>
import { goBack } from 'svelte-native'
</script>
To cause the back to happen on another frame, pass in a frame reference or id to the frame
option.
goBack({ frame: 'sub-nav-frame' })
goBack
by default goes back to the previous page, you can go back multiple pages if you specify a page
reference in options.
goBack({ to: options_page_ref })
showModal
To show a page or component modally use the showModal
function. Specify the page to open using the page
option and props using the props
option (just like in navigate).
<page>
<actionBar title="Master" />
<stackLayout>
<button text="Open Modal" on:tap="{launchModal}" />
</stackLayout>
</page>
<script>
import DetailPage from './DetailPage.svelte'
import { showModal } from 'svelte-native'
function launchModal() {
showModal({ page: DetailPage, props: { msg: 'hi' } })
}
</script>
<frame id="detail-page-frame">
<page>
<label text="Detail Page" />
</page>
</frame>
The other options available correspond directly to those in ShowModalOptions and are passed through to the underlying NativeScript showModal method.
The showModal
function returns a promise which resolves to whatever is passed to closeModal
.
NOTE The modal is opened in a new navigation context. If you want to allow navigation within the modal, or show an action bar, you will need to wrap the target page in a
frame
element. If you don't need any navigation within the modal then this won't be necessary.
closeModal
The closeModal
function closes the current modal view and optionally returns a value to the caller of the original showModal
via a promise result.
<page>
<actionBar title="Master" />
<stackLayout>
<button text="Open Modal" on:tap="{launchModal}" />
<label text="{modalResult}" />
</stackLayout>
</page>
<script>
import DetailPage from './DetailPage.svelte'
import { showModal } from 'svelte-native'
let modalResult = "Waiting for modal"
async function launchModal() {
let result = await showModal({ page: DetailPage, props: { msg: 'hi' } })
modalResult = `got result: ${result}`
}
</script>
<frame id="detail-page-frame">
<page>
<button text="Close me" on:tap="{ () => closeModal('hi from modal') }" />
</page>
</frame>
<script>
import { closeModal } from 'svelte-native'
</script>
Utilities
Template Component
The <Template>
svelte component lets you define markup that is reused as a template. It is currently used to render listItems in the <listView>
component.
Basic usage
<page>
<listView items="{items}">
<Template let:item={i}>
<label text="{i}" />
</Template>
</listView>
</page>
<script>
import { Template } from 'svelte-native/components'
let items = ['one', 'two', 'three']
</script>
NOTE The template element here has a capital
T
and is imported fromsvelte-native/components
. This is because it is a Svelte component not a NativeScript element.
Advanced usage
You can use Template
to implement custom NativeScript elements that require a template or multiple templates.
When Template
is rendered by svelte, it outputs a special DOM element called template
which has a component
attribute. Implementations such as svelte native's binding to listView
look for the template
elements and use the component to instantiate and render the template content.
Any extra properties added to the Template
component are passed down and added to the template
DOM element.
For a concrete example of this pattern see svelte native's listView element source.
Property Element
Some NativeScript controls have properties that expect NativeScript views as values. To make this possible using markup, Svelte Native introduce two helpers, the property element and the prop
directive.
This property element works like the ones in the NativeScript core documentation and set some property of their parent view with the value of the first child of the property element. The tag name is the name of the parent element followed by the property name. For example <page.actionbar>
would set the actionbar
property of the parent page
element.
An Example
The <radSideDrawer>
component is part of the Progress NativeScript UI package.
The <radSideDrawer>
component requires the drawerContent
and mainContent
properties to be set to View
instances. Using Property Elements, you can do this with a few lines of code:
<radSideDrawer>
<radSideDrawer.drawerContent>
<stackLayout />
</radSideDrawer.drawerContent>
<radSideDrawer.mainContent>
<stackLayout />
</radSideDrawer.mainContent>
</radSideDrawer>
Without the Property Elements, you need to go a more tedious and error-prone route:
<radSideDrawer bind:this="{drawer}">
<stackLayout bind:this="{drawerContent}" />
<stackLayout bind:this="{mainContent}" />
</radSideDrawer>
import { onMount } from 'svelte'
let drawer
let drawerContent
let mainContent
onMount(() => {
drawer.nativeView.mainContent = mainContent.nativeView
drawer.nativeView.drawerContent = drawerContent.nativeView
})
Property Directive
The Property Element is useful but can be a little verbose. Svelte native also introduces a custom svelte directive called prop
. The prop directive will take the native view of the component it is on an assign it to a property of the parent element.
For example our side drawer example from Property Element
<radSideDrawer>
<radSideDrawer.drawerContent>
<stackLayout />
</radSideDrawer.drawerContent>
<radSideDrawer.mainContent>
<stackLayout />
</radSideDrawer.mainContent>
</radSideDrawer>
can be written using the prop element as
<radSideDrawer>
<stackLayout prop:drawerContent />
<stackLayout prop:mainContent/>
</radSideDrawer>
Implicit Property Directives
Many advanced controls (including those in the nativescript-ui packages) use elements to provide configuration. These configuration properties need to be assigned to a parent property but often only have one valid parent property to which they can be assigned, so the prop:
or Property Element becomes boilerplate
Take this example from nativescript-ui-dataform
:
<radDataForm source={ticket} metadata={ticketMetadata}>
<entityProperty prop:properties name="price" index="4" readOnly="true">
<propertyEditor prop:editor type="Decimal" />
</entityProperty>
<entityProperty prop:properties name="numberOfTickets" displayName="Number of Tickets" index="5">
<propertyEditor prop:editor type="Stepper">
<propertyEditorParams prop:params minimum="0" maximum="100" step="2" />
</propertyEditor>
</entityProperty>
</radDataForm>
on a large form, the prop:properties
prop:editor
and prop:params
can get repetitive. Svelte Native lets you register a configuration element with a default property name for the prop:
directive. When this is set, the prop:
directive is not needed at all:
<radDataForm source={ticket} metadata={ticketMetadata}>
<entityProperty name="price" index="4" readOnly="true">
<propertyEditor type="Decimal" />
</entityProperty>
<entityProperty name="numberOfTickets" displayName="Number of Tickets" index="5">
<propertyEditor type="Stepper">
<propertyEditorParams minimum="0" maximum="100" step="2" />
</propertyEditor>
</entityProperty>
</radDataForm>
Layouts
AbsoluteLayout
The <absoluteLayout>
container is the simplest layout container in NativeScript.
<absoluteLayout>
has the following behavior:
- Uses a pair of absolute left/top coordinates to position its children.
- Doesn't enforce any layout constraints on its children.
- Doesn't resize its children at runtime when its size changes.
Examples
A grid-like layout
The following example creates a simple grid. For more information about creating grid layouts, see GridLayout.
<absoluteLayout backgroundColor="#3c495e">
<label text="10,10" left="10" top="10" width="100" height="100" backgroundColor="#4383b8"/>
<label text="120,10" left="120" top="10" width="100" height="100" backgroundColor="#4383b8"/>
<label text="10,120" left="10" top="120" width="100" height="100" backgroundColor="#4383b8"/>
<label text="120,120" left="120" top="120" width="100" height="100" backgroundColor="#4383b8"/>
</absoluteLayout>
Overlapping elements
The following example creates a group of overlapping items.
<absoluteLayout backgroundColor="#3c495e">
<label text="10,10" left="10" top="10" width="100" height="100" backgroundColor="#286290"/>
<label text="30,40" left="30" top="40" width="100" height="100" backgroundColor="#4383b8"/>
</absoluteLayout>
Additional children props
When an element is a direct child of <absoluteLayout>
, you can work with the following additional properties.
Name | Type | Description |
---|---|---|
top |
Number |
Gets or sets the distance, in pixels, between the top edge of the child and the top edge of its parent. |
left |
Number |
Gets or sets the distance, in pixels, between the left edge of the child and the left edge of its parent. |
DockLayout
<dockLayout>
is a layout container that lets you dock child elements to the sides or the center of the layout.
<dockLayout>
has the following behavior:
- Uses the
dock
property to dock its children to theleft
,right
,top
,bottom
or center of the layout.
To dock a child element to the center, it must be the last child of the container and you must set thestretchLastChild
property of the parent totrue
. - Enforces layout constraints to its children.
- Resizes its children at runtime when its size changes.
Examples
Dock to every side without stretching the last child
The following example creates a frame-like layout consisting of 4 elements, position at the 4 edges of the screen.
<dockLayout stretchLastChild="false" backgroundColor="#3c495e">
<label text="left" dock="left" width="40" backgroundColor="#4383b8"/>
<label text="top" dock="top" height="40" backgroundColor="#286290"/>
<label text="right" dock="right" width="40" backgroundColor="#4383b8"/>
<label text="bottom" dock="bottom" height="40" backgroundColor="#286290"/>
</dockLayout>
Dock to every side and stretch the last child
The following example shows how stretchLastChild
affects the positioning of child elements in a DockLayout
container. The last child (bottom
) is stretched to take up all the remaining space after positioning the first three elements.
<dockLayout stretchLastChild="true" backgroundColor="#3c495e">
<label text="left" dock="left" width="40" backgroundColor="#4383b8"/>
<label text="top" dock="top" height="40" backgroundColor="#286290"/>
<label text="right" dock="right" width="40" backgroundColor="#4383b8"/>
<label text="bottom" dock="bottom" backgroundColor="#1c486b"/>
</dockLayout>
Dock to every side and the center
The following example creates a <dockLayout>
of 5 elements. The first four wrap the center element in a frame.
<dockLayout stretchLastChild="true" backgroundColor="#3c495e">
<label text="left" dock="left" width="40" backgroundColor="#4383b8"/>
<label text="top" dock="top" height="40" backgroundColor="#286290"/>
<label text="right" dock="right" width="40" backgroundColor="#4383b8"/>
<label text="bottom" dock="bottom" height="40" backgroundColor="#286290"/>
<label text="center" backgroundColor="#1c486b" />
</dockLayout>
Dock multiple children to the same side
The following example creates a single line of 4 elements that stretch across the entire height and width of the screen.
<dockLayout stretchLastChild="true" backgroundColor="#3c495e">
<label text="left 1" dock="left" width="40" backgroundColor="#4383b8"/>
<label text="left 2" dock="left" width="40" backgroundColor="#286290"/>
<label text="left 3" dock="left" width="40" backgroundColor="#1c486b"/>
<label text="last child" backgroundColor="#4383b8"/>
</dockLayout>
Props
Name | Type | Description |
---|---|---|
stretchLastChild |
Boolean |
Enables or disables stretching the last child to fit the remaining space. |
Additional children props
When an element is a direct child of <dockLayout>
, you can work with the following additional properties.
Name | Type | Description |
---|---|---|
dock |
String |
Specifies which side to dock the element to. Valid values: top , right , bottom , or left . |
FlexboxLayout
<flexboxLayout>
is a layout container that provides a non-exact implementation of the CSS Flexbox layout. This layout lets you arrange child components both horizontally and vertically.
Examples
Default flex layout
The following example creates a row of three equally-sized elements that span across the entire height of the screen.
<flexboxLayout backgroundColor="#3c495e">
<label text="first" width="70" backgroundColor="#4383b8"/>
<label text="second" width="70" backgroundColor="#1c486b"/>
<label text="third" width="70" backgroundColor="#286290"/>
</flexboxLayout>
Column flex layout
The following example creates a column of three equally-sized elements that span across the entire width of the screen.
<flexboxLayout flexDirection="column" backgroundColor="#3c495e">
<label text="first" height="70" backgroundColor="#4383b8"/>
<label text="second" height="70" backgroundColor="#1c486b"/>
<label text="third" height="70" backgroundColor="#286290"/>
</flexboxLayout>
Row flex layout with items aligned to flex-start
The following example creates a row of three items placed at the top of the screen. Items are placed in the order they were declared in.
<flexboxLayout alignItems="flex-start" backgroundColor="#3c495e">
<label text="first" width="70" height="70" backgroundColor="#4383b8"/>
<label text="second" width="70" height="70" backgroundColor="#1c486b"/>
<label text="third" width="70" height="70" backgroundColor="#286290"/>
</flexboxLayout>
Row flex layout with custom order
The following example creates a row of three items placed at the top of the screen. Items are placed in a customized order.
<flexboxLayout alignItems="flex-start" backgroundColor="#3c495e">
<label text="first" order="2" width="70" height="70" backgroundColor="#4383b8"/>
<label text="second" order="3" width="70" height="70" backgroundColor="#1c486b"/>
<label text="third" order="1" width="70" height="70" backgroundColor="#286290"/>
</flexboxLayout>
Row flex layout with wrapping
The following example creates four items with enabled line wrapping. When the row runs out of space, the container wraps the last item on a new line.
<flexboxLayout flexWrap="wrap" backgroundColor="#3c495e">
<label text="first" width="30%" backgroundColor="#4383b8"/>
<label text="second" width="30%" backgroundColor="#1c486b"/>
<label text="third" width="30%" backgroundColor="#286290"/>
<label text="fourth" width="30%" backgroundColor="#286290"/>
</flexboxLayout>
Column flex layout with reverse order and items with a different alignSelf
The following example shows how to use:
flexDirection
to place items in a column, starting from the bottom.justifyContent
to create equal spacing between the vertically placed items.alignSelf
to modify the position of items across the main axis.
<flexboxLayout flexDirection="column-reverse"
justifyContent="space-around" backgroundColor="#3c495e">
<label text="first" height="70" backgroundColor="#4383b8"/>
<label text="second" alignSelf="center" width="70" height="70" backgroundColor="#1c486b"/>
<label text="third\nflex-end" alignSelf="flex-end" width="70" height="70" backgroundColor="#286290"/>
<label text="fourth" height="70" backgroundColor="#286290"/>
</flexboxLayout>
Props
Name | Type | Description |
---|---|---|
flexDirection |
String |
Sets the direction for placing child elements in the flexbox container. Valid values: row (horizontal, left to right),row-reverse (horizontal, right to left),column (vertical, top to bottom), andcolumn-reverse (vertical, bottom to top).Default value: row . |
flexWrap |
String |
Sets whether child elements are forced in a single line or can flow into multiple lines. If set to multiple lines, also defines the cross axis which determines the direction new lines are stacked in. Valid values: nowrap (single line which may cause the container to overflow),wrap (multiple lines, direction is defined by flexDirection ), andwrap-reverse (multiple lines, opposite to the direction defined by flexDirection ).Default value: nowrap . |
justifyContent |
String |
Sets the alignment of child elements along the main axis. You can use it to distribute leftover space when all the child elements on a line are inflexible or are flexible but have reached their maximum size. You can also use it to control the alignment of items when they overflow the line. Valid values: flex-start (items are packed toward the start line),flex-end (items are packed toward the end line),center (items are centered along the line),space-between (items are evenly distributed on the line; first item is on the start line, last item on the end line), andspace-around (items are evenly distributed on the line with equal space around them).Default value: flex-start . |
alignItems |
String |
(Android-only) Sets the alignment of child elements along the cross axis on the current line. Acts as justifyContent for the cross axis.Valid values: flex-start (cross-start margin edge of the items is placed on the cross-start line),flex-end (cross-end margin edge of the items is placed on the cross-end line),center (items are centered оn the cross axis),baseline (the item baselines are aligned), andstretch (items are stretched to fill the container but respect min-width and max-width ).Default value: stretch . |
alignContent |
String |
Sets how lines are aligned in the flex container on the cross axis, similar to how justifyContent aligns individual items within the main axis.This property has no effect when the flex container has only one line. Valid values: flex-start (lines are packed to the start of the container),flex-end (lines are packed to the end of the container),center (lines are packed to the center of the container),space-between (lines are evenly distributed; the first line is at the start of the container while the last one is at the end),space-around (lines are evenly distributed with equal space between them), andstretch (lines are stretched to take up the remaining space).Default value: stretch . |
Additional children props
When an element is a direct child of <flexboxLayout>
, you can work with the following additional properties.
Name | Type | Description |
---|---|---|
order |
Number |
Sets the order in which child element appear in relation to one another. |
flexGrow |
Number |
Indicates that the child should grow in size, if necessary. Sets how much the child will grow in proportion to the rest of the child elements in the flex container. |
flexShrink |
Number |
Indicates that the child should shrink when the row runs out of space. Sets how much the flex item will shrink in proportion to the rest of the child elements in the flex container. When not specified, its value is set to 1 . |
alignSelf |
String |
(Android-only) Overrides the alignItems value for the child.Valid values: flex-start (cross-start margin edge of the item is placed on the cross-start line),flex-end (cross-end margin edge of the item is placed on the cross-end line),center (item is centered on the cross axis),baseline (the item baselines are aligned), andstretch (item is stretched to fill the container but respects min-width and max-width ).Default value: stretch . |
flexWrapBefore |
Boolean |
When true , forces the item to wrap onto a new line. This property is not part of the official Flexbox specification.Default value: false . |
GridLayout
<gridLayout>
is a layout container that lets you arrange its child elements in a table-like manner.
The grid consists of rows, columns, and cells. A cell can span one or more rows and one or more columns. It can contain multiple child elements which can span over multiple rows and columns, and even overlap each other.
By default, <gridLayout>
has one column and one row. You can add columns and rows by configuring the columns
and the rows
properties. In these properties, you need to set the number of columns and rows and their width and height. You set the number of columns by listing their widths, separated by a comma. You set the number of rows by listing their heights, separated by a comma.
You can set a fixed size for column width and row height or you can create them in a responsive manner:
- An absolute number: Indicates a fixed size.
- auto: Makes the column as wide as its widest child or makes the row as tall as its tallest child.
- *: Takes as much space as available after filling all auto and fixed size columns or rows.
Examples
Grid layout with fixed sizing
The following example creates a simple 2-by-2 grid with fixed column widths and row heights.
<gridLayout columns="115, 115" rows="115, 115">
<label text="0,0" row="0" col="0" backgroundColor="#4383b8"/>
<label text="0,1" row="0" col="1" backgroundColor="#1c486b"/>
<label text="1,0" row="1" col="0" backgroundColor="#286290"/>
<label text="1,1" row="1" col="1" backgroundColor="#4383b8"/>
</gridLayout>
Grid layout with star sizing
The following example creates a grid with responsive design, where space is alotted proportionally to child elements.
<gridLayout columns="*, 2*" rows="2*, 3*" backgroundColor="#3c495e">
<label text="0,0" row="0" col="0" backgroundColor="#4383b8"/>
<label text="0,1" row="0" col="1" backgroundColor="#1c486b"/>
<label text="1,0" row="1" col="0" backgroundColor="#286290"/>
<label text="1,1" row="1" col="1" backgroundColor="#4383b8"/>
</gridLayout>
Grid layout with fixed and auto sizing
The following example create a grid with one auto-sized column and one column with fixed size. Rows have a fixed height.
<gridLayout columns="80, auto" rows="80, 80" backgroundColor="#3c495e">
<label text="0,0" row="0" col="0" backgroundColor="#4383b8"/>
<label text="0,1" row="0" col="1" backgroundColor="#1c486b"/>
<label text="1,0" row="1" col="0" backgroundColor="#286290"/>
<label text="1,1" row="1" col="1" backgroundColor="#4383b8"/>
</gridLayout>
Grid layout with mixed sizing and merged cells
The following example creates a complex grid with responsive design, mixed width and height settings, and some merged cells.
<gridLayout columns="40, auto, *" rows="40, auto, *" backgroundColor="#3c495e">
<label text="0,0" row="0" col="0" backgroundColor="#4383b8"/>
<label text="0,1" row="0" col="1" colSpan="2" backgroundColor="#1c486b"/>
<label text="1,0" row="1" col="0" rowSpan="2" backgroundColor="#286290"/>
<label text="1,1" row="1" col="1" backgroundColor="#4383b8"/>
<label text="1,2" row="1" col="2" backgroundColor="#286290"/>
<label text="2,1" row="2" col="1" backgroundColor="#1c486b"/>
<label text="2,2" row="2" col="2" backgroundColor="#4383b8"/>
</gridLayout>
Props
Name | Type | Description |
---|---|---|
columns |
String |
A string value representing column widths delimited with commas. Valid values: an absolute number, auto , or * .A number indicates an absolute column width. auto makes the column as wide as its widest child. * makes the column occupy all available horizontal space. The space is proportionally divided over all star-sized columns. You can set values such as 3* and 5* to indicate a ratio of 3:5 in sizes. |
rows |
String |
A string value representing row heights delimited with commas. Valid values: an absolute number, auto , or * .A number indicates an absolute row height. auto makes the row as tall as its tallest child. * makes the row occupy all available vertical space. The space is proportionally divided over all star-sized rows. You can set values such as 3* and 5* to indicate a ratio of 3:5 in sizes. |
Additional children props
When an element is a direct child of <gridLayout>
, you can work with the following additional properties.
Name | Type | Description |
---|---|---|
row |
Number |
Specifies the row for this element. Combined with a col property, specifies the cell coordinates of the element.The first row is indicated by 0 . |
col |
Number |
Specifies the column for the element. Combined with a row property, specifies the cell coordinates of the element.The first column is indicated by 0 . |
rowSpan |
Number |
Specifies the number of rows that this element spans across. |
colSpan |
Number |
Specifies the number of columns that this element spans across. |
StackLayout
<stackLayout>
is a layout container that lets you stack the child elements vertically (default) or horizontally.
Examples
Default stacking
The following example creates a vertical stack of 3 equally-sized elements. Items are stretched to cover the entire width of the screen. Items are placed in the order they were declared in.
<stackLayout backgroundColor="#3c495e">
<label text="first" height="70" backgroundColor="#4383b8"/>
<label text="second" height="70" backgroundColor="#286290"/>
<label text="third" height="70" backgroundColor="#1c486b"/>
</stackLayout>
Horizontal stacking
The following example creates a horizontal stack of 3 equally-sized elements. Items are stretched to cover the entire height of the screen. Items are placed in the order they were declared in.
<stackLayout orientation="horizontal" backgroundColor="#3c495e">
<label text="first" width="70" backgroundColor="#4383b8"/>
<label text="second" width="70" backgroundColor="#286290"/>
<label text="third" width="70" backgroundColor="#1c486b"/>
</stackLayout>
Stack layout with horizontally aligned children
The following example creates a diagonal stack of items with responsive sizes. Items are vertically stacked.
<stackLayout backgroundColor="#3c495e">
<label text="left" horizontalAlignment="left"
width="33%" height="70" backgroundColor="#4383b8"/>
<label text="center" horizontalAlignment="center"
width="33%" height="70" backgroundColor="#286290"/>
<label text="right" horizontalAlignment="right"
width="33%" height="70" backgroundColor="#1c486b"/>
<label text="stretch" horizontalAlignment="stretch"
height="70" backgroundColor="#4383b8"/>
</stackLayout>
Horizontal stack layout with vertically aligned children
The following example creates a diagonal stack of items with responsive sizes. Items are horizontally stacked.
<stackLayout orientation="horizontal" backgroundColor="#3c495e">
<label text="top" verticalAlignment="top"
width="70" height="33%" backgroundColor="#4383b8"/>
<label text="center" verticalAlignment="center"
width="70" height="33%" backgroundColor="#286290"/>
<label text="bottom" verticalAlignment="bottom"
width="70" height="33%" backgroundColor="#1c486b"/>
<label text="stretch" verticalAlignment="stretch"
width="70" backgroundColor="#4383b8"/>
</stackLayout>
Props
Name | Type | Description |
---|---|---|
orientation |
String |
Specifies the stacking direction. Valid values: vertical and horizontal .Default value: vertical . |
WrapLayout
<wrapLayout>
is a layout container that lets you position items in rows or columns, based on the orientation
property. When the space is filled, the container automatically wraps items onto a new row or column.
Examples
Default wrap layout
The following example creates a row of equally-sized items. When the row runs out of space, the container wraps the last item on a new row.
<wrapLayout backgroundColor="#3c495e">
<label text="first" width="30%" height="30%" backgroundColor="#4383b8"/>
<label text="second" width="30%" height="30%" backgroundColor="#1c486b"/>
<label text="third" width="30%" height="30%" backgroundColor="#286290"/>
<label text="fourth" width="30%" height="30%" backgroundColor="#286290"/>
</wrapLayout>
Vertical wrap layout
The following example creates a column of equally-sized items. When the row runs out of space, the container wraps the last item on a new column.
<wrapLayout orientation="vertical" backgroundColor="#3c495e">
<label text="first" width="30%" height="30%" backgroundColor="#4383b8"/>
<label text="second" width="30%" height="30%" backgroundColor="#1c486b"/>
<label text="third" width="30%" height="30%" backgroundColor="#286290"/>
<label text="fourth" width="30%" height="30%" backgroundColor="#286290"/>
</wrapLayout>
Props
Name | Type | Description |
---|---|---|
orientation |
String |
Specifies the stacking direction. Valid values: horizontal (arranges items in rows) and vertical (arranges items in columns).Default value: horizontal . |
itemWidth |
Number |
Sets the width used to measure and layout each child. Default value: Number.NaN , which does not restrict children. |
itemHeight |
Number |
Sets the height used to measure and layout each child. Default value is Number.NaN , which does not restrict children. |
RootLayout
<rootLayout>
is a layout container designed to be used as the primary root layout container for your app with a built in api to easily control dynamic view layers. It extends a GridLayout so has all the features of a grid but enhanced with additional apis.
Its api can be observed here:
export class RootLayout extends GridLayout {
open(view: View, options?: RootLayoutOptions): Promise<void>
close(view: View, exitTo?: TransitionAnimation): Promise<void>
bringToFront(view: View, animated?: boolean): Promise<void>
closeAll(): Promise<void>
getShadeCover(): View
}
export function getRootLayout(): RootLayout
export interface RootLayoutOptions {
shadeCover?: ShadeCoverOptions
animation?: {
enterFrom?: TransitionAnimation
exitTo?: TransitionAnimation
}
}
export interface ShadeCoverOptions {
opacity?: number
color?: string
tapToClose?: boolean
animation?: {
enterFrom?: TransitionAnimation // only applied if first one to be opened
exitTo?: TransitionAnimation // only applied if last one to be closed
}
ignoreShadeRestore?: boolean
}
export interface TransitionAnimation {
translateX?: number
translateY?: number
scaleX?: number
scaleY?: number
rotate?: number // in degrees
opacity?: number
duration?: number // in milliseconds
curve?: any // CoreTypes.AnimationCurve (string, cubicBezier, etc.)
}
You can use getRootLayout()
to get a reference to the root layout in your app from anywhere.
Example: RootLayout setup
Sample layout:
<rootLayout height="100%" width="100%">
<gridLayout height="100%">
<label
verticalAlignment="center"
textAlignment="center"
text="MAIN CONTENT AREA"
></label>
</gridLayout>
</rootLayout>
Sample api usage:
// Open a dynamic popup
const view = this.getPopup('#EA5936', 110, -30)
getRootLayout()
.open(view, {
shadeCover: {
color: '#000',
opacity: 0.7,
tapToClose: true
},
animation: {
enterFrom: {
opacity: 0,
translateY: 500,
duration: 500
},
exitTo: {
opacity: 0,
duration: 300
}
}
})
.catch(ex => console.error(ex))
// Close the dynamic popup
getRootLayout()
.close(view, {
opacity: 0,
translate: { x: 0, y: -500 }
})
.catch(ex => console.error(ex))
function getPopup(color: string, size: number, offset: number): View {
const layout = new StackLayout()
layout.height = size
layout.width = size
layout.marginTop = offset
layout.marginLeft = offset
layout.backgroundColor = color
layout.borderRadius = 10
return layout
}
ActionBars
ActionBar
<actionBar>
is a UI component that provides a toolbar at the top of the activity window.
This component is the NativeScript abstraction for the Android app bar and the iOS navigation bar.
Using a title
<actionBar title="MyApp" />
Using a custom title view
<actionBar>
<stackLayout orientation="horizontal">
<image src="res://icon" width="40" height="40" verticalAlignment="center" />
<label text="NativeScript" fontSize="24" verticalAlignment="center" />
</stackLayout>
</actionBar>
Setting an app icon for Android
<actionBar title="My App" android.icon="res://icon" android.iconVisibility="always" />
Removing the border
By default, a border is drawn at the bottom of the <actionBar>
. In addition to the border, on iOS devices a translucency filter is also applied over the <actionBar>
.
To remove this styling from your app, you can set the flat
property to true
.
<actionBar title="My App" flat="true" />
Props
Name | Type | Description |
---|---|---|
title |
String |
Gets or sets the title shown in the bar. |
android.icon |
String |
Gets or sets the icon to be shown on Android devices. |
android.iconVisibility |
String |
Gets or sets icon visibility on Android devices. |
flat |
boolean |
Removes the border on Android and the translucency on iOS. Default value is false . |
Native component
Android | iOS |
---|---|
android.widget.Toolbar |
UINavigationBar |
ActionItem
<actionItem>
is a UI component that lets you add action buttons to the <actionBar>
component.
Basic use
<actionBar title="My App">
<actionItem on:tap="{onTapShare}"
ios.systemIcon="9" ios.position="left"
android.systemIcon="ic_menu_share" android.position="actionBar" />
<actionItem on:tap="{onTapDelete}"
ios.systemIcon="16" ios.position="right"
text="delete" android.position="popup" />
</actionBar>
Props
Name | Type | Description |
---|---|---|
ios.systemIcon |
Number |
Gets or sets the icon of the ActionItem for iOS. The value must be a number from the UIBarButtonSystemItem.SystemItem enumeration. |
android.systemIcon |
String |
Gets or sets the icon of the ActionItem for Android. The value must be the name of a drawable resource. |
ios.position |
String |
Gets or sets the position of the ActionItem within the ActionBar for iOS.Valid values: left or right .Default value is left . |
android.position |
String |
Gets or sets the position of the ActionItem within the ActionBar for Android.Valid values: actionBar (places the item in the ActionBar),popup (places the item in the options menu; renders items as text), andactionBarIfRoom (places the item in the ActionBar if there is enough room for it there; otherwise, places it in the options menu).Default value is actionBar . |
Events
Name | Description |
---|---|
tap |
Emitted when the ActionItem is tapped. |
Native component
Android | iOS |
---|---|
android.widget.Toolbar |
UINavigationItem |
NavigationButton
<navigationButton>
is a UI component that provides an abstraction for the Android navigation button and the iOS back button.
Extends <actionItem>
.
<actionBar title="My App">
<navigationButton text="Go back" android.systemIcon="ic_menu_back" on:tap="{goBack}" />
</actionBar>
Props
Name | Type | Description |
---|---|---|
text |
String |
(iOS-only) Sets the text of the button. |
android.systemIcon |
String |
(Android-only) The icon to be shown in the button. You can specify any system icon whose name begins with the ic_ prefix. For a complete list of the available icons, see the R.drawable Android class. |
Events
Name | Description |
---|---|
tap |
Emitted when the <navigationButton> is tapped. |
Native component
Android | iOS |
---|---|
android.widget.Toolbar |
UINavigationItem |
Tab Navigation
NOTE: Svelte-Native < 1.0.0 only. NativeScript 8 has removed these components from core, in favour of the community managed implementations @nativescript-community/ui-material-tabs and @nativescript-community/ui-material-bottom-navigation which are drop in replacements.
TabStrip
The TabStrip component is only valid within BottomNavigation
or Tabs
components. It contains a set of TabStripItem
elements which specify the configuration of the tabs within the parent tab view.
<tabStrip>
<tabStripItem>
<label text="Home" />
<image src="font://" class="fas t-36" />
</tabStripItem>
<tabStripItem>
<label text="Account" />
<image src="font://" class="fas t-36" />
</tabStripItem>
</tabStrip>
Props
Name | Type | Description |
---|---|---|
iosIconRenderingMode |
"automatic", "alwaysOriginal", "alwaysTemplate" |
Gets or sets the icon rendering mode on iOS. |
isIconSizeFixed |
Boolean |
When set to true the icon will have fixed size following the platform-specific design guidelines. Default value: true . |
Events
Name | Description |
---|---|
itemTap |
Emitted when a TabStripItem is tapped. |
TabStripItem
Tab strip items define the display of a tab selector within a TabStrip
. They may contain a Label
and/or Image
tag.
<tabStrip>
<tabStripItem>
<label text="Home" />
<image src="font://" class="fas t-36" />
</tabStripItem>
...
</tabStrip>
Props
Name | Type | Description |
---|---|---|
title |
string |
Gets or sets the title of the tab strip entry. |
iconSource |
string |
Gets or sets the icon source of the tab strip entry. Supports local image paths (~), resource images (res://) and icon fonts (font://). |
Events
Name | Description |
---|---|
tap |
Emitted when a TabStripItem is tapped. |
TabContentItem
A TabContentItem
contains the view to be displayed when the corresponding TabStripItem is selected.
NOTE: Currently,
TabContentItem
expects a single child element. In most cases, you might want to wrap your content in a layout.
<tabContentItem>
<stackLayout>
<label text="Hello From This Tab" />
</stackLayout>
</tabContentItem>
Props
None
Events
None
Bottom Navigation
The BottomNavigation component is a cross-platform implementation of the Bottom Navigation UI from the Material Design Guidelines. Ideal for use when there are 3 to 5 tabs each with their own function.
It can contain a single TabStrip
child (which contains multiple TabStripItems), and multiple TabContentItem
children (corresponding to each TabStripItem).
<bottomNavigation bind:selectedIndex={selectedTab}>
<!-- The bottom tab UI is created via TabStrip (the containier) and TabStripItem (for each tab)-->
<tabStrip>
<tabStripItem>
<label text="Home" />
<image src="font://" class="fas t-36" />
</tabStripItem>
<tabStripItem class="special">
<label text="Account" />
<image src="font://" class="fas t-36" />
</tabStripItem>
<tabStripItem class="special">
<label text="Search" />
<image src="font://" class="fas t-36" />
</tabStripItem>
</tabStrip>
<!-- The number of TabContentItem components should corespond to the number of TabStripItem components -->
<tabContentItem>
<gridLayout>
<label text="Home Page" class="h2 text-center" />
</gridLayout>
</tabContentItem>
<tabContentItem>
<gridLayout>
<label text="Account Page" class="h2 text-center" />
</gridLayout>
</tabContentItem>
<tabContentItem>
<gridLayout>
<label text="Search Page" class="h2 text-center" />
</gridLayout>
</tabContentItem>
</bottomNavigation>
Props
Name | Type | Description |
---|---|---|
selectedIndex |
number |
Gets or sets the selectedIndex of the BottomNavigation. |
Events
Name | Description |
---|---|
selectedIndexChanged |
Emitted when the selectedIndex property is changed. |
loaded |
Emitted when the view is loaded. |
unloaded |
Emitted when the view is unloaded. |
layoutChanged |
Emitted when the layout bounds of a view change due to layout processing. |
Native component
Android | iOS |
---|---|
FrameLayout |
UITabViewController |
Tabs
The Tabs component is a cross-platform implementation of the Tabs UI from the Material Design Guidelines. It is recommended for mid level navigation.
It can contain a single TabStrip
child (which contains multiple TabStripItems), and multiple TabContentItem
children (corresponding to each TabStripItem).
Unlike the Bottom Navigation
component, the tabs component is made for tabs with a common function and supports transitions and gestures.
<tabs bind:selectedIndex={selectedTab}>
<!-- The bottom tab UI is created via TabStrip (the containier) and TabStripItem (for each tab)-->
<tabStrip>
<tabStripItem>
<label text="Home" />
<image src="font://" class="fas t-36" />
</tabStripItem>
<tabStripItem class="special">
<label text="Account" />
<image src="font://" class="fas t-36" />
</tabStripItem>
<tabStripItem class="special">
<label text="Search" />
<image src="font://" class="fas t-36" />
</tabStripItem>
</tabStrip>
<!-- The number of TabContentItem components should corespond to the number of TabStripItem components -->
<tabContentItem>
<gridLayout>
<label text="Home Page" class="h2 text-center" />
</gridLayout>
</tabContentItem>
<tabContentItem>
<gridLayout>
<label text="Account Page" class="h2 text-center" />
</gridLayout>
</tabContentItem>
<tabContentItem>
<gridLayout>
<label text="Search Page" class="h2 text-center" />
</gridLayout>
</tabContentItem>
</tabs>
Props
Name | Type | Description |
---|---|---|
selectedIndex |
number |
Gets or sets the selectedIndex of the BottomNavigation. |
tabsPosition |
"top", "bottom" |
Gets or sets the position state of the Tabs. Default value: top . |
Events
Name | Description |
---|---|
selectedIndexChanged |
Emitted when the selectedIndex property is changed. |
loaded |
Emitted when the view is loaded. |
unloaded |
Emitted when the view is unloaded. |
layoutChanged |
Emitted when the layout bounds of a view change due to layout processing. |
Native component
Android | iOS |
---|---|
FrameLayout |
UITabViewController |
Components
ActivityIndicator
<activityIndicator>
is a UI component that shows a progress indicator signaling to the user of an operation running in the background.
<activityIndicator busy="{true}" on:busyChange="{onBusyChanged}" />
Props
Name | Type | Description |
---|---|---|
busy |
Boolean |
Gets or sets whether the indicator is active. When true , the indicator is active. |
Events
Name | Description |
---|---|
busyChange |
Emitted when the busy property is changed. |
Native Component Reference
Android | iOS |
---|---|
android.widget.ProgressBar |
UIActivityIndicatorView |
Button
<button>
is a UI component that displays a button which reacts to a user gesture.
For more information about the available gestures, see Gestures in the official NativeScript documentation.
<button text="Button" on:tap="{onButtonTap}" />
Props
Name | Type | Description |
---|---|---|
text |
String |
Sets the label of the button. |
textWrap |
Boolean |
Gets or sets whether the widget wraps the text of the label. Useful for longer labels. Default value is false . |
Events
Name | Description |
---|---|
tap |
Emitted when the button is tapped. |
Native Component Reference
Android | iOS |
---|---|
android.widget.Button |
UIButton |
DatePicker
<datePicker>
is a UI component that lets users select a date from a pre-configured range.
<datePicker date="{someDate}" />
<datePicker>
provides two-way data binding using bind
.
<datePicker bind:date="{selectedDate}" />
See also: TimePicker.
Props
Name | Type | Description |
---|---|---|
date |
Date |
Gets or sets the complete date. |
minDate |
Date |
Gets or sets the earliest possible date to select. |
maxDate |
Date |
Gets or sets the latest possible date to select. |
day |
Number |
Gets or sets the day. |
month |
Number |
Gets or sets the month. |
year |
Number |
Gets or sets the year. |
Events
Name | Description |
---|---|
dateChange |
Emitted when the selected date changes. |
Native Component Reference
Android | iOS |
---|---|
android.widget.DatePicker |
UIDatePicker |
Frame
<frame>
is a UI component used to display <page>
elements. Every app needs at least a single <frame>
element, usually set as the root element. Svelte Native creates the root frame for you.
If you need to create multiple frames, you can do so by wrapping them in a Layout, for example if you want to have 2 frames side-by-side.
<gridLayout columns="*, *">
<frame col="0"/>
<frame col="1"/>
</gridLayout>
The first child element of a frame will become its defaultPage
. This is the page shown before any navigation.
<frame>
<page>
<actionBar title="Default Page Title" />
<gridLayout>
<label text="Default Page Content" />
</gridLayout>
</page>
</frame>
You can use a component as the default page for a frame, as long as it defines page
as its root element.
<frame>
<Home />
</frame>
import Home from './Home.svelte'
Native Component Reference
Android | iOS |
---|---|
org.nativescript.widgets.ContentLayout |
UINavigationController |
HtmlView
<htmlView>
is a UI component that lets you show static HTML content.
See also: WebView.
<htmlView html="<div><h1>HtmlView</h1></div>" />
Props
Name | Type | Description |
---|---|---|
html |
String |
The HTML content to be shown. |
Native Component Reference
Android | iOS |
---|---|
android.widget.TextView |
UITextView |
Image
<image>
is a UI component that shows an image from an ImageSource or from a URL.
NativeScript aliases ~
to the app directory.
<image src="~/logo.png" stretch="none" />
Images can be loaded from external URLs.
<image src="https://svelte-native.technology/media/todoapp/todo-add-item.png" stretch="none" />
Images can also be displayed from the App_Resources folder using the res://
scheme.
<image src="res://icon" stretch="none" />
NativeScript also supports data URIs that are base64 encoded.
<image src="data:Image/png;base64,iVBORw..." stretch="none" />
Props
Name | Type | Description |
---|---|---|
src |
String or ImageSource |
Gets or sets the source of the image as a URL or an image source. |
imageSource |
ImageSource |
Gets or sets the image source of the image. |
tintColor |
Color |
(Style property) Sets a color to tint template images. |
stretch |
Stretch |
(Style property) Gets or sets the way the image is resized to fill its allocated space. Valid values: none , aspectFill , aspectFit , or fill .For more information, see Stretch. |
loadMode |
Gets or sets the loading strategy for the images on the local file system. Valid values: sync or async .Default value: async .For more information, see loadMode. |
Native Component Reference
Android | iOS |
---|---|
android.widget.ImageView |
UIImageView |
Label
<label>
is a UI component that displays read-only text.
IMPORTANT: This
<label>
is not the same as the HTML<label>
.
<label text="Label" />
Styling the label
If you need to style parts of the text, you can use a combination of a FormattedString
and Span
elements.
<label textWrap="{true}">
<formattedString>
<span text="This text has a " />
<span text="red " style="color: red" />
<span text="piece of text. " />
<span text="Also, this bit is italic, " fontStyle="italic" />
<span text="and this bit is bold." fontWeight="bold" />
</formattedString>
</label>
Props
Name | Type | Description |
---|---|---|
text |
String |
Gets or sets the text of the label. |
textWrap |
Boolean |
Gets or sets whether the label wraps text. Default value: false . |
Native Component Reference
Android | iOS |
---|---|
android.widget.TextView |
UILabel |
ListPicker
<listPicker>
is a UI component that lets the user select a value from a pre-configured list.
<listPicker items="{listOfItems}" selectedIndex="0"
on:selectedIndexChange="{selectedIndexChanged}" />
<script>
let listOfItems = ['one', 'two', 'three']
const selectedIndexChanged = (e) => console.log(e.index)
</script>
<listPicker>
provides two-way data binding for selectedIndex.
<listPicker items="{listOfItems}" bind:selectedIndex={selectedItem}" />
Props
Name | Type | Description |
---|---|---|
items |
Array<string> |
Gets or sets the items displayed as options in the list picker. |
selectedIndex |
Number |
Gets or sets the index of the currently selected item. |
Events
Name | Description |
---|---|
selectedIndexChange |
Emitted when the currently selected option (index) changes. |
Native Component Reference
Android | iOS |
---|---|
android.widget.NumberPicker |
UIPickerView |
ListView
<listView>
is a UI component that shows items in a vertically scrolling list. To set how the list shows individual items, you use the <Template>
component.
<listView items="{listOfItems}" on:itemTap="{onItemTap}">
<Template let:item>
<!-- Shows the list item label in the default color and style. -->
<label text="{item}" />
</Template>
</listView>
<script>
import { Template } from 'svelte-native/components'
let listOfItems = ['one', 'two', 'three']
</script>
<listView>
does not loop through list items as you would expect when using a regular svelte each
block. Instead <listView>
only creates the necessary views to display the currently visible items on the screen, and reuses the views that are already off-screen when scrolled. This concept is called view recycling and is commonly used in mobile apps to improve performance.
You can use the itemTap
event which provides the index of the tapped item.
function onItemTap(event) {
console.log(event.index) //item index
}
Multiple Templates Selector Function
Multiple templates can be used for different layouts of list items, which is similar to NativeScript Multiple Templates Selector Function. itemTemplateSelector
is used to select template using key
which is returned based on your logic.
Note: Use multiple templates approach instead of
{#if}
block, because the view recycling concept does not work as intended since<listView>
cannot reuse the same template view if off-screen items require different type of template. See this article
<listView items={items} itemTemplateSelector={selectTemplate}>
<Template let:item key="odd">
<label text="Odd {item}" />
</Template>
<Template let:item key="even">
<label text="Even {item}" />
</Template>
</listView>
<script>
import { Template } from 'svelte-native/components'
let items = ["item 0", "item 1"]
function selectTemplate(item, index, items) {
// Your logic here
return (index % 2 == 0) ? "even" : "odd";
}
</script>
IMPORTANT NOTE: unlike Svelte expressions, The
<listView>
will not update the item list if you assign the same value to lists (eglistOfItems.push('four'); listOfItems = listOfItems
). It will update if you assign a new list reference (eglistOfItems = listOfItems.concat('four')
orlistOfItems = [...listOfItems, 'four']
).
Props
Name | Type | Description |
---|---|---|
items |
Array<any> |
An array of items to be shown in the <listView> . |
separatorColor |
Color |
Sets the separator line color. Set to transparent to remove it. |
itemTemplateSelector |
(item,index,items) => string |
(optional) returns the key to the template to use for the provided item. |
Events
Name | Description |
---|---|
itemTap |
Emitted when an item in the <listView> is tapped. To access the index of the tapped item, use event.index . |
Native Component Reference
Android | iOS |
---|---|
android.widget.ListView |
UITableView |
Page
<page>
is a UI component that represents an application screen. NativeScript apps typically consist of one or more <page>
elements that wrap content such as an <actionBar>
and other UI widgets.
<page>
<actionBar title="My App" />
<gridLayout>
<label text="My Content"/>
</gridLayout>
</page>
Props
Name | Type | Description |
---|---|---|
actionBarHidden |
Boolean |
Shows or hides the <actionBar> for the page.Default value: false . |
backgroundSpanUnderStatusBar |
Boolean |
Gets or sets whether the background of the page spans under the status bar. Default value: false . |
androidStatusBarBackground |
Color |
(Android-only) Gets or sets the color of the status bar on Android devices. |
enableSwipeBackNavigation |
Boolean |
(iOS-only) Gets or sets whether the page can be swiped back on iOS. Default value: true . |
statusBarStyle |
String |
Gets or sets the style of the status bar. Valid values: light ,dark . |
Events
Name | Description |
---|---|
navigatedFrom |
Emitted after the app has navigated away from the current page. |
navigatedTo |
Emitted after the app has navigated to the current page. |
navigatingFrom |
Emitted before the app has navigated away from the current page. |
navigatingTo |
Emitted before the app has navigated to the current page. |
Native Component Reference
Android | iOS |
---|---|
org.nativescript.widgets.GridLayout |
UIViewController |
Progress
<progress>
is a UI component that shows a bar to indicate the progress of a task.
See also: ActivityIndicator.
<progress value="{currentProgress}" />
Props
Name | Type | Description |
---|---|---|
value |
Number |
Gets or sets the current value of the progress bar. Must be within the range of 0 to maxValue . |
maxValue |
Number |
Gets or sets the maximum value of the progress bar. Default value: 100 . |
Events
Name | Description |
---|---|
valueChange |
Emitted when the value property changes. |
Native Component Reference
Android | iOS |
---|---|
android.widget.ProgressBar (indeterminate = false) |
UIProgressView |
ScrollView
<scrollView>
is a UI component that shows a scrollable content area. Content can be scrolled vertically or horizontally.
<scrollView orientation="horizontal">
<stackLayout orientation="horizontal">
<label text="this" />
<label text="text" />
<label text="scrolls" />
<label text="horizontally" />
<label text="if necessary" />
</stackLayout>
</scrollView>
Props
name | type | description |
---|---|---|
orientation |
String |
Gets or sets the direction in which the content can be scrolled: horizontal or vertical .Default value: vertical . |
scrollBarIndicatorVisible |
Boolean |
Specifies if the scrollbar is visible. Default value: true . |
Events
Name | Description |
---|---|
scroll |
Emitted when a scroll event occurs. |
Native Component Reference
Android | iOS |
---|---|
android.view |
UIScrollView |
SearchBar
<searchBar>
is a UI component that provides a user interface for entering search queries and submitting requests to the search provider.
<searchBar hint="Search hint" text="{searchQuery}" on:textChange="{onTextChanged}" on:submit="{onSubmit}" />
<searchBar>
provides two-way data binding for text
.
<searchBar bind:text="{searchQuery}" />
Props
Name | Type | Description |
---|---|---|
hint |
String |
Gets or sets placeholder text for the input area. |
text |
String |
Gets or sets the value of the search query. |
textFieldBackgroundColor |
Color |
Gets or sets the background color of the input area. |
textFieldHintColor |
Color |
Gets or sets the color of the placeholder text. |
Events
name | description |
---|---|
textChange |
Emitted when the text is changed. |
submit |
Emitted when the search input is submitted. |
clear |
Emitted when the current search input is cleared through the X button in the input area. |
Native Component Reference
Android | iOS |
---|---|
android.widget.SearchView |
UISearchBar |
SegmentedBar
<segmentedBar>
is a UI bar component that displays a set of buttons for discrete selection. It can show text or images.
As opposed to <tabView>
:
- The position of
<segmentedBar>
is not fixed. - You can place and style it as needed on the page or inside additional app elements such as hamburger menus.
- You need to handle the content shown after selection separately.
<segmentedBar>
<segmentedBarItem title="First" />
<segmentedBarItem title="Second" />
<segmentedBarItem title="Third" />
</segmentedBar>
<segmentedBar selectedIndex="0"
on:selectedIndexChange="{onSelectedIndexChange}" >
<segmentedBar>
can be populated with {each}
block.
<segmentedBar>
{#each listOfItems as item}
<segmentedBarItem title="{item}" />
{/each}
</segmentedBar>
<script>
let listOfItems = [ 'First', 'Second', 'Third' ];
</script>
<segmentedBar>
provides two-way data binding of selectedIndex
.
<segmentedBar bind:selectedIndex="{selectedItem}" >
Props
Name | Type | Description |
---|---|---|
items |
Array<segmentedBarItem> |
An array of items to be displayed in the segmented bar. Represents the button labels or icons of the segmented bar. The array must be created in advance. |
selectedIndex |
Number |
Gets or sets the index of the selected item. |
selectedBackgroundColor |
Color |
(Style property) Gets or sets the background color of the selected item. To set the background color of the entire bar, use backgroundColor . |
Events
Name | Description |
---|---|
selectedIndexChange |
Emitted when an item on the segmented bar is tapped. |
Native Component Reference
Android | iOS |
---|---|
android.widget.TabHost |
UISegmentedControl |
Slider
<slider>
is a UI component that provides a slider control for picking values within a specified numeric range.
<slider value="80" on:valueChange="{onValueChanged}" />
<slider>
provides two-way data binding of value
:
<slider bind:value="{value}" />
Props
Name | Type | Description |
---|---|---|
value |
Number |
Gets or sets the currently selected value of the slider. Default value: 0 . |
minValue |
Number |
Gets or sets the minimum value of the slider. Default value: 0 . |
maxValue |
Number |
Gets or sets the maximum value of the slider. Default value: 100 . |
Events
Name | Description |
---|---|
valueChange |
Emitted when the value of the slider changes. |
Native Component Reference
Android | iOS |
---|---|
android.widget.SeekBar |
UISlider |
Switch
<switch>
is a UI component that lets users toggle between two states.
The default state is false
or OFF.
<switch checked="{true}" on:checkedChange={onCheckedChange} />
<switch>
provides two-way data binding for checked
.
<switch bind:checked="{switchEnabled}" />
Props
Name | Type | Description |
---|---|---|
checked |
Boolean |
Gets or sets the value of the switch selection. Default value: false . |
Events
Name | Description |
---|---|
checkedChange |
Emitted when the switch selection changes. |
Native Component Reference
Android | iOS |
---|---|
android.widget.Switch |
UISwitch |
TabView
NOTE: TabView should be considered obsolete as of NS 6.1. Please use
BottomNavigation
orTabs
<tabView>
is a navigation component that shows content grouped into tabs and lets users switch between tabs.
<tabView selectedIndex="{selectedIndex}" on:selectedIndexChange="{indexChange}">
<tabViewItem title="Tab 1">
<label text="Content for Tab 1" />
</tabViewItem>
<tabViewItem title="Tab 2">
<label text="Content for Tab 2" />
</tabViewItem>
</tabView>
function indexChange(event) {
let newIndex = event.value
console.log('Current tab index: ' + newIndex)
}
NOTE: Currently,
<tabViewItem>
expects a single child element. In most cases, you might want to wrap your content in a layout.
Adding icons to tabs
<tabView selectedIndex="{selectedIndex}" iosIconRenderingMode="alwaysOriginal">
<tabViewItem title="Tab 1" iconSource="~/images/icon.png">
<label text="Content for Tab 1" />
</tabViewItem>
<tabViewItem title="Tab 2" iconSource="~/images/icon.png">
<label text="Content for Tab 2" />
</tabViewItem>
</tabView>
NOTE: You can use images for tab icons instead of icon fonts. For more information about how to control the size of icons, see Working with image from resource folders.
Props
Name | Type | Description |
---|---|---|
selectedIndex |
Number |
Gets or sets the currently selected tab. Default is 0 . |
tabTextColor |
Color |
(Style property) Gets or sets the text color of the tabs titles. |
tabBackgroundColor |
Color |
(Style property) Gets or sets the background color of the tabs. |
selectedTabTextColor |
Color |
(Style property) Gets or sets the text color of the selected tab title. |
androidTabsPosition |
String |
Sets the position of the TabView in Android platform Valid values: top or bottom . |
Events
Name | Description |
---|---|
selectedIndexChange |
Emits an event object containing a value property with the index of the tapped <tabViewItem> . |
Native Component Reference
Android | iOS |
---|---|
android.support.v4.view.ViewPager |
UITabBarController |
TextField
<textField>
is an input component that creates an editable single-line box.
<textField>
extends TextBase
and EditableTextBase
which provide additional properties and events.
<textField text="{textFieldValue}" hint="Enter text..." />
<textField>
provides two-way data binding using bind
.
<textField bind:text="{textFieldValue}" />
Props
Name | Type | Description |
---|---|---|
text |
String |
Gets or sets the value of the field. |
hint |
String |
Gets or sets the placeholder text. |
editable |
Boolean |
When true , indicates that the user can edit the value of the field. |
maxLength |
Number |
Limits input to the spcified number of characters. |
secure |
Boolean |
Hides the entered text when true . Use this property to create password input fields.Default value: false . |
keyboardType |
KeyboardType |
Shows a custom keyboard for easier text input. Valid values: datetime , phone , number , url , or email . |
returnKeyType |
ReturnKeyType |
Gets or sets the label of the return key. Valid values: done , next , go , search , or send . |
autocorrect |
Boolean |
Enables or disables autocorrect. |
Events
Name | Description |
---|---|
textChange |
Emitted when the text changes. |
returnPress |
Emitted when the return key is pressed. |
focus |
Emitted when the field is in focus. |
blur |
Emitted when the field loses focus. |
Native Component Reference
Android | iOS |
---|---|
android.widget.EditText |
UITextField |
TextView
<textView>
is a UI component that shows an editable or a read-only multi-line text container. You can use it to let users type large text in your app or to show longer, multi-line text on the screen.
<textView>
extends TextBase
and EditableTextBase
which provide additional properties and events.
<textView text="Multi\nLine\nText" />
<textView>
provides two-way data binding using bind
.
<textView bind:text="{textViewValue}" />
Displaying multi-style text
To apply multiple styles to the text in your <textView>
, you can use <formattedString>
.
<textView editable="{false}">
<formattedString>
<span text="You can use text attributes such as " />
<span text="bold, " fontWeight="Bold" />
<span text="italic " fontStyle="Italic" />
<span text="and " />
<span text="underline." textDecoration="Underline" />
</formattedString>
</textView>
Props
Name | Type | Description |
---|---|---|
text |
String |
Gets or sets the value of the component. |
hint |
String |
Gets or sets the placeholder text when the component is editable. |
editable |
Boolean |
When true , indicates that the user can edit the contents of the container. |
maxLength |
Number |
Sets the maximum number of characters that can be entered in the container. |
keyboardType |
KeyboardType |
Shows a custom keyboard for easier text input. Valid values: datetime , phone , number , url , or email . |
returnKeyType |
Gets or sets the label of the return key. Currently supported only on iOS. Valid values: done , next , go , search , or send . |
|
autocorrect |
Boolean |
Enables or disables autocorrect. |
Events
Name | Description |
---|---|
textChange |
Emitted when the text changes. |
returnPress |
Emitted when the return key is pressed. |
focus |
Emitted when the container is in focus. |
blur |
Emitted when the container loses focus. |
Native Component Reference
Android | iOS |
---|---|
android.widget.EditText |
UITextView |
TimePicker
<timePicker>
is a UI component that lets users select time.
See also: DatePicker.
<timePicker hour="{selectedHour}" minute="{selectedMinute}" />
<timePicker>
provides two-way data binding using bind
.
<timePicker bind:time="{selectedTime}" />
Props
Name | Type | Description |
---|---|---|
hour |
Number |
Gets or sets the selected hour. |
minute |
Number |
Gets or sets the selected minute. |
time |
Date |
Gets or sets the selected time. |
minHour |
Number |
Gets or sets the minimum selectable hour. |
maxHour |
Number |
Gets or sets the maximum selectable hour. |
minMinute |
Number |
Gets or sets the minimum selectable minute. |
maxMinute |
Number |
Gets or sets the maximum selectable minute. |
minuteInterval |
Number |
Gets or sets the selectable minute interval. For example: 5 or 15 minutes. Default value: 1 . |
Events
Name | Description |
---|---|
timeChange |
Emitted when the selected time changes. |
Native Component Reference
Android | iOS |
---|---|
android.widget.TimePicker |
UIDatePicker |
WebView
<webView>
is a UI component that lets you show web content in your app. You can pull and show content from a URL or a local HTML file, or you can render static HTML content.
See also: HtmlView.
<webView src="http://nativescript-vue.org/" />
<webView src="~/html/index.html" />
<webView src="<div><h1>Some static HTML</h1></div>" />
Props
Name | Type | Description |
---|---|---|
src |
String |
Gets or sets the displayed web content. Valid values: an absolute URL, the path to a local HTML file, or static HTML. |
Events
Name | Description |
---|---|
loadStarted |
Emitted when the page has started loading in the <webView> . |
loadFinished |
Emitted when the page has finished loading in the <webView> . |
Native Component Reference
Android | iOS |
---|---|
android.webkit.WebView |
WKWebView |
Dialogs
ActionDialog
The action()
method shows a list of selectable options and a cancellation button. Use it to let the user choose between options or dismiss the selection.
The method is part of the dialogs
module.
Basic use
import { action } from '@nativescript/core/ui/dialogs'
action('Your message', 'Cancel button text', ['Option1', 'Option2'])
.then(result => {
console.log(result)
})
AlertDialog
The alert()
method shows a message and an OK button. Use it to show information and notifications that do not require an action from the user.
The method is part of the dialogs
module.
Basic use
import { alert } from '@nativescript/core/ui/dialogs'
alert('Your message')
.then(() => {
console.log("Alert dialog closed.")
})
Configure dialog options
alert({
title: "Your title",
message: "Your message",
okButtonText: "Your OK button text"
}).then(() => {
console.log("Alert dialog closed")
})
ConfirmDialog
The confirm()
method shows a confirmation message and Cancel and OK buttons.
The method is part of the dialogs
module.
Basic use
import { confirm } from '@nativescript/core/ui/dialogs'
confirm('Your message')
.then(res => {
console.log(res)
})
Configure dialog options
confirm({
title: "Your title",
message: "Your message",
okButtonText: "Your OK button text",
cancelButtonText: "Your Cancel text"
}).then(res => {
console.log(res)
})
LoginDialog
The login()
method shows a dialog where the user can provide login credentials.
The method is part of the dialogs
module.
Basic use
import { login } from '@nativescript/core/ui/dialogs'
login("Your message", "Username field value", "Password field value")
.then(res => {
console.log(`Dialog result: ${res.result}, user: ${res.userName}, pwd: ${res.password}`)
})
Configure dialog options
login({
title: "Your login title",
message: "Your login message",
okButtonText: "Your OK button text",
cancelButtonText: "Your Cancel button text",
userName: "Username field value",
password: "Password field value"
}).then(res => {
console.log(`Dialog result: ${res.result}, user: ${res.userName}, pwd: ${res.password}`)
})
PromptDialog
The prompt()
method shows a dialog with a single-line field for user input.
The method is part of the dialogs
module.
Basic use
import { prompt } from '@nativescript/core/ui/dialogs'
prompt('Your message to the user', 'Suggested user input')
.then(res => {
console.log(`Dialog result: ${res.result}, text: ${res.text}`)
})
Configure dialog options
prompt({
title: "Your dialog title",
message: "Your message",
okButtonText: "Your OK button text",
cancelButtonText: "Your Cancel button text",
defaultText: "Suggested user input",
}).then(res => {
console.log(`Dialog result: ${res.result}, text: ${res.text}`)
})
Configure input type
You can also configure the input type using inputType
. You can choose between plain text (text
), email-enabled input (email
), and password-like hidden input (password
), number input for numeric keyboard (number
or decimal
) and phone number (phone
).
inputType: inputType.text
inputType: inputType.email
inputType: inputType.password
inputType: inputType.number
inputType: inputType.decimal
inputType: inputType.phone
You can control the capitalization type for prompt dialog. This will control the shift behavior on the input keyboard.
capitalizationType: capitalizationType.none
capitalizationType: capitalizationType.all
capitalizationType: capitalizationType.sentences
capitalizationType: capitalizationType.words
Example
import { prompt, inputType } from '@nativescript/core/ui/dialogs'
prompt({
title: "Email Prompt",
message: "Provide your email address:",
okButtonText: "OK",
cancelButtonText: "Cancel",
defaultText: "name@domain.com",
inputType: inputType.email
}).then(res => {
console.log(`Dialog result: ${res.result}, text: ${res.text}`)
})
TODO...
This documentation is still a work-in-progress, like Svelte Native itself. If there are particular things that are missing or could be improved, then please raise an issue on GitHub!