问题描述
在我的 Nativescript Angular 应用程序中,我在 ScrollView 中有一个 TextView,定义如下:
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.
目前,每当我向绑定 TextView 的 terminalText
变量添加一些文本时,ScrollView 就会滚动回顶部.我希望能够将 ScrollView 保留在 TextView 的底部.
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.
一些注意事项:
我通过此方法向关联组件类中的 terminalText
变量添加文本:
I am adding text to the terminalText
variable within my associated component class through this method:
public appendToTerminal(appendStr){
this.terminalText += appendStr;
}
我已经尝试实现以下代码,一旦 ScrollView 加载就会执行:
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);
}
}
(此尝试基于此处
我只在 Android 设备上尝试过这个,因为我无法访问 Apple 设备.
I have only tried this on an Android device, as I do not have access to an Apple device.
推荐答案
您正在将 TextView
设置为固定高度 100%,这将与 ScrollView
相同,这就是为什么scrollableHeight
将始终为 0.您应该使用 minHeight="100%"
.
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%"
.
然后您可以在将文本附加到终端文本 this.terminalText += appendStr
时以编程方式滚动到末尾.
then you can scroll programmatically to the end when you are appending text to terminal text this.terminalText += appendStr
.
喜欢这个
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.
这里是操场演示:https://play.nativescript.org/?template=play-ng&id=Rs0xnP&v=16
这篇关于Nativescript以编程方式滚动到ScrollView的底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!