Sunday, 9 August 2015

Making an image button in nativescript

In the latest release on nativescript, background-image, background-position, background-repeat, background-size, border-radius styles were added.

So I decided to make the buttons in my app a bit more visually interesting. I was inspired by a tweet from John Bristowe.

This is how my buttons originally looked, simple black squares.

Css for this is as below.

.button {
    horizontal-align: center;
    margin: 5;
    color: white;
    background-color: black;

I wasn't really happy with the spacing for the cancel button. I tried to use padding, but this isn't supported in buttons because of it being just simple text, not an object which can have padding.

So I eventually ended up with this.

.buttonImage {
    horizontal-align: center;
    margin: 5;
    color: white;
    background-color: black;
    background-repeat : no-repeat;
    background-position : left center;

I also wrote a custom extension to the button class.

import button = require("ui/button");

export class ImageButton extends button.Button {
    private _icon: string;

    // icon

    public get icon(): string {
        return this._icon;

    public set icon(value: string) {
        this._icon = value;

        this.cssClass = "buttonImage";
        this.backgroundImage = "~/res/icons/white/" + value + "_white.png";

    // text override with spacing

    public get textPadded(): string {
        return this._getValue(button.Button.textProperty);

    public set textPadded(value: string) {
        this._setValue(button.Button.textProperty, "       " + value + "  ");

It adds in padding before and after the text, to make it fit the button and avoid overlapping the image. This depends on the font and image you use obviously. Ideally it should be done with padding, but this will not work unfortunately. You can pass in the icon name you want to use in XML.

You can declare widgets at the top of your page like this.

<Page xmlns="" xmlns:check="helpers/checkboximage">

You can then reference them in XML layout.

<imageButton:ImageButton textPadded="{{languageData.OK}}" tap="{{ok}}" icon="tick"/>

So the end result is I can now have buttons like below. I think this looks more visually appealing.

No comments:

Post a Comment