Nativescript以编程方式滚动到ScrollView的底部

Ins*_*kat 3 nativescript angular2-nativescript

在我的Nativescript Angular应用程序中,我在ScrollView中有一个TextView,其定义如下:

<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>
Run Code Online (Sandbox Code Playgroud)

该元素的作用是充当终端,并快速打印来自蓝牙设备的传入消息。

当前,每当我terminalText向TextView绑定到的变量中添加一些文本时,ScrollView就会滚动回到顶部。我希望能够将ScrollView保留在TextView的底部。


一些注意事项:

我正在terminalText通过此方法向关联的组件类中的变量添加文本:

public appendToTerminal(appendStr){
    this.terminalText += appendStr;
}
Run Code Online (Sandbox Code Playgroud)

我尝试实现以下代码,这些代码将在ScrollView加载后执行:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

(此尝试基于此处给出的说明

我只能在Android设备上尝试此操作,因为我无法访问Apple设备。

bha*_*ara 7

您将TextView固定高度设置为100%,这与ScrollView为什么scrollableHeight将高度始终设置为0 是相同的minHeight="100%"。您应该使用。

然后在将文本追加到终端文本时,可以通过编程方式滚动到末尾this.terminalText += appendStr

像这样

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

    },150);
}
Run Code Online (Sandbox Code Playgroud)

这将附加文本,然后获取scrollableHeight,然后滚动至该文本。

这是工作操场的演示:https : //play.nativescript.org/?template= play-ng &id=Rs0xnP&v=16

  • 尝试了你的方法,还是不行。我可能已经找到了原因 - 我记录了scrollView的值,它是scrollableHeight,虽然scrollView很好,但scrollableHeight始终设置为0,即使我可以手动向下滚动页面。对此有何评论?我尝试将“TextView”嵌入“StackLayout”中,但也没有成功。 (2认同)