Nativescript scroll to bottom of ScrollView programmatically

冷暖自知 提交于 2019-12-05 22:14:46

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

The function below can only be used in the Angular ngDoCheck() or ngAfterContentChecked() lifecycle:

// See https://angular.io/guide/lifecycle-hooks
function goDownScrollView(scrollView: object, animate: boolean = true): boolean {

    let neScrollView:     ScrollView = <ScrollView>getNativeElement(scrollView),
        scrollableHeight: number     = neScrollView.scrollableHeight;

    console.log("neScrollView:", neScrollView);
    console.log("neScrollView scrollableHeight:", scrollableHeight);

    if (scrollableHeight > 0) {

        neScrollView.scrollToVerticalOffset(scrollableHeight, animate);
        return true;

    } else {

        return false;

    }

}

An helper to always get the native element:

function getNativeElement(object: object): object {

    return (object.hasOwnProperty("nativeElement")) ? object['nativeElement'] : object;

}

The scrollable height may be zero at the first pass of the lifecycle (for example, if you add elements to your ScrollView with an HTTP request). That's why you have to test the current content with new before scroll:

// See https://angular.io/api/core/ViewChild
@ViewChild("content") private _pageContent: ElementRef<ScrollView>;

public  currentContent:   object;
private _previousContent: object;

...

ngAfterContentChecked(): void {

    if (this.currentContent != this._previousContent) {

        let isScrollDown: boolean = goDownScrollView(this._pageContent);

        if (isScrollDown) {

            this._previousContent = this.currentContent;

        }

    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!