1

NativeScript supports using custom fonts that are packaged in the app's app/fonts directory. One refers to them with CSS font-family rules. I need to be able to use a custom font that is loaded from a web site at run time.

In native Android, one can load a font more or less directly from a web address (just open an input stream to the URL and feed it to the Typeface constructor). In iOS, it's also possible (as per this thread). Is there any support for doing something similar in NS (use a custom font loaded from the web), other than dropping down into native code?

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521

1 Answers1

3

This actually is pretty simple to do in NativeScript; however there is a gotcha if you don't want to duplicate any code. You must put the fonts in the /app/fonts folder, even the ones you download.

Your steps are:

  1. Download the font to the /app/fonts/ folder, you can use any valid method to download it/them.
    Unfortunately, the font registration system looks for any custom fonts in the fonts folder; so unless you want to "duplicate" the registration code in your own code base; just drop the new fonts into the /app/fonts/ folder.
  2. Register the font for ios:

if (!global.android) { var fonts = require('ui/styling/fonts'); fonts.ios.registerFont('MyFont.ttf'); // or .otf }

  1. Assign a MyFont directly to the item's style property; (i.e. SomeLabel.style.fontFamily = "MyFont";)

or

  1. assign the font-family to a css value; and then assign the css Page.addCss('MyCoolFont { font-family: myFont; }"); to the SomeLabel.cssClass = 'myCoolFont';
Nathanael
  • 5,369
  • 18
  • 23
  • I guess I'm too stuck in Android development mode, where the app's resources are read-only. I didn't even think of simply putting the font file into `app/fonts`. Thanks! – Ted Hopp Dec 07 '16 at 12:33
  • For future-proofing, wouldn't it be better to test `if (global.ios)` instead of `if (!global.android)`? – Ted Hopp Dec 07 '16 at 12:40
  • Yeah, I put a suggestion in to the NS team over a year ago to publish a `global.ios` in the ios engine, but they disagreed with me. I still think they are wrong. :-) You can use `global.android` on android... Other platforms don't have as convenient of a method. You can `require ('platforms')` and detect it that way, or you can use things like: `if (typeof NSString !== 'undefined' && typeof NSObject !== 'undefined') // on ios` – Nathanael Dec 08 '16 at 00:09