Saturday, June 25, 2016

How to set up Icons that displays differently amid iOS and Android devices


Hello folks,

We've already mentioned how great and powerful Ionic framework is. But it has several useful functions such as ionic.Platform.isAndroid(), ionic.Platform.isIOS(),  and ionic.Platform.isWindowsPhone()
that might be extremely helpful to you use within your code to detect which icon to use. That's a great feature that we can not skip and the reason why I've created this article just for that.

An example of this is:

var iconThiagoLeoncio;

if (ionic.Platform.isAndroid()) {
  iconThiagoLeoncio = 'ion-android-arrow-back';
} else if (ionic.Platform.isIOS()) {
  iconThiagoLeoncio = 'ion-ios-arrow-back';
} else {
  iconThiagoLeoncio = 'ion-android-arrow-back';
}


In practice, I am going to to do a simpler check. If it is Android, use the Android icon, otherwise use IOS. This won’t work as neatly if you want to specify ionic.Platform.isWindowsPhone() ,
 however so far Ionicons have no Windows Phone specific icons so I am using Android icons as standard coding project:


var iconThiagoLeoncio = ionic.Platform.isIOS() ? 'ion-ios-arrow-back' : 'ion-android-arrow-back';


When this is in objects by itself, I am going to use regularly, I am turning the object into a directive which contains this logic specifically.
For example, a custom back button (replace starter with the global app name you use for your modules in such):

angular.module('starter.directives', [])
    .directive('backbutton', [function () {
        return {
            restrict: 'E',
            replace: true,
            scope: false,
            template: '<button class="button icon button-clear"></button>',

            compile: function (element, attrs) {
                var iconThiagoLeoncio = ionic.Platform.isIOS() ? 'ion-ios-arrow-back' : 'ion-android-arrow-back';
                angular.element(element[0]).addClass(iconThiagoLeoncio);
            }
        };
    }])


This code above creates the the element below:


<backbutton ng-click="goBack()"></backbutton>

With that in mind and in your code you can reuse across many different apps and we can keep this in sych(updated) with any new changes in your location.

Very important to mention in here:
There is a back button element in Ionic, however we are creating our own simpler version for some situations, for example a custom modal windows in your project.
Keep in mind this great example just works for any other button and icons you might want to use as well.

Another IONIC article on my blog:  Ionic How to get started with Ionic

happy coding,
Thiago Leoncio

No comments:

Post a Comment