Search code examples
layoutpluginsnativescript

How to add an absolute element in a NativeScript page


I want to be able to just place a View component (plugin) into the page through code and have it appear at some X\Y on the page... but I'm a bit stumped.

Any attempt to add via page.content kinda adds it to the layout\render pass so it occupies space.

So this would get injected into "any" page at "any" time, I have no control over the markup this would be used in (know what I mean?) There is no XML for it and unfortunately the answer can't just be wrap everything in an AbsoluteLayout because one can't mandate that on users apps\layouts.

Thoughts, even possible?


Solution

  • Basically the simplest way to do this is to dynamically and be fully cross platform compatible is to create a AbsoluteLayout item in your JavaScript code, and dynamically insert your item and the AL into the page container.

    Code would be something like this:

    var AbsoluteLayout = require('ui/layouts/absolute-layout').AbsoluteLayout;
    var myAL = new AbsoluteLayout();
    var myItem = new myPluginItem();
    
    // Set you left, right, top, bottom coords.
    myItem.top = x;
    
    // Add our item to the AbsoluteItem
    myAL.addChild(myItem);
    
    var frame = require('ui/frame');
    var page = frame.topmost().currentPage;
    var LayoutBase = require('ui/layouts/layout-base').LayoutBase;
    
    page._eachChildView(function(view) {
      if (view instanceof LayoutBase) {
         view.addChild(myAL); 
         return false;
      } 
      return true;
    });
    

    However, if you don't want to do this the really simple way; the only other way is to actually go a bit lower level. You can natively access the iOS view controller (page._ios.view) and the android view (page._nativeView), and then manually add it to the view by using things like addView (https://developer.android.com/reference/android/view/ViewManager.html) or addSubview (https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/).