Setting frame of view with Javascript


#1

I’m struggling to figure out how to position a view in the page on iOS.

I don’t want to use an AbsoluteLayout for the reasons described here: Absolute/Fixed positioning without AbsoluteLayout

Is it possible to set the frame of a view using Javascript?

I’ve tried the following but it doesn’t seem to work. I see the label added to the page but my frame is ignored.

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="onLoaded" navigatedTo="onNavigatedTo" class="page">
    <StackLayout id="test">
        
    </StackLayout>
</Page>

And the js:

var labelModule = require("ui/label");

var page;

exports.onLoaded = function(args) {
    page = args.object;
}

exports.onNavigatedTo = function(args) {
    var test = page.getViewById('test');

    positionEl(test);    
}

function positionEl(el) {
    var myLabel = new labelModule.Label();
    myLabel.text = 'My label';
    myLabel.ios.frame = {origin: {x:200, y:200}, size: {width: 200, height:200}};

    el.addChild(myLabel);
}

I’ve just come across view._setNativeViewFrame() but again, this doesn’t seem to work:

myLabel._setNativeViewFrame(myLabel.ios, {origin: {x:50, y:100}, size: {width: 200, height:600}});

#2

Hello, mate. I’ve checked your previous topic (the one regarding absolute layouts) and I’ve got some suggestions to you. They’re not directly related to this frame problem though haha. In summary you’re trying to add error indicators for a label, right?

Every text field of yours is explicitly declared on your xml, so why not positioning your indicator in the xml as well right after your text field? You could trigger its visibility based on the results of the user’s input.

Say you have a password input and the password must be between 6 and 12 characters length. You could display the indicator when the length is less than 6, greater than 12 and not display otherwise.

My second suggestion is to create this indicator as a custom component (https://docs.nativescript.org/ui/basics#custom-components), so you could write once and reuse whenever you need. The component could be added to your xml as a tag and you could pass specific attributes to it (height, width, message) depending on how you design the component.

Hope theses suggestions help. If you have any question message me and I will try to help you.

Cheers.


#3

Hi @rcluan,

I did consider declaring the indicator in the markup but I don’t want it to take up any space in the layout when it is shown. I need it to behave like position: absolute would in CSS. ie. removed from the layout. From what I can see the closest approximation of position: absolute is to use an AbsoluteLayout which isn’t quite the same.