Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nativescript scroll to bottom of ScrollView programmatically

In my Nativescript Angular application, I have a TextView within a ScrollView, defined as such:

<ScrollView orientation="vertical" height="70%" width="100%" style="margin-bottom: 1%; background-color:white" (loaded)="onScrollerLoaded($event)">
    <TextView 
        id="terminal" [text]="terminalText" editable="false"
        style="color: whitesmoke; background-color: black; font-size: 8%; font-family: monospace" height="100%"     
        (tap)="onTap($event)" (loaded)="onTerminalLoaded($event)">
    </TextView>
</ScrollView>

The purpose of this element is to act as a terminal, and is rapidly printing incoming messages from a bluetooth device.

Currently, the ScrollView is scrolling back to the top whenever I add some text to the terminalText variable, to which the TextView is bound. I would like to be able to keep the ScrollView at the bottom of the TextView.


A few notes:

I am adding text to the terminalText variable within my associated component class through this method:

public appendToTerminal(appendStr){
    this.terminalText += appendStr;
}

I have tried implementing the following code that would execute once the ScrollView loads:

private scrollIntervalId;
onScrollerLoaded(data: EventData){
    if(!this.scrollIntervalId){
        this.scrollIntervalId = setInterval(()=>{
            this.ngZone.run(() =>
                (data.object as any).scrollToVerticalOffset((data.object as any).scrollableHeight, false)
            )
        }, 10);
    }
}

(This attempt is based on an explanation given here

I have only tried this on an Android device, as I do not have access to an Apple device.

like image 760
Instakat Avatar asked Jan 03 '23 04:01

Instakat


1 Answers

you are setting TextView to fixed height 100% which is will be same as ScrollView that is why scrollableHeight will always be 0. you should use minHeight="100%".

then you can scroll programmatically to the end when you are appending text to terminal text this.terminalText += appendStr.

like this

public appendToTerminal(appendStr){
    this.terminalText += appendStr;
    setTimeout(()=>{
        scrollView.scrollToVerticalOffset(scrollView.scrollableHeight, false);

    },150);
}

this will append the text then get the scrollableHeight and then will scroll to it.

here is working playground demo:https://play.nativescript.org/?template=play-ng&id=Rs0xnP&v=16

like image 194
bhavin jalodara Avatar answered May 01 '23 14:05

bhavin jalodara