nativescript - 确定组件是否在屏幕中可见
问题描述
我使用 Nativescript + Angular,这是我的代码:
<ScrollView class="body" id="scroll" #scroll (scroll)="scrollEvent($event);">
<StackLayout #stackScroll>
<ng-template ngFor let-card [ngForOf]="allList">
<StackLayout [card]="card">
<my-custom-component [aCard]="card"></my-custom-component>
</StackLayout>
</ng-template>
</StackLayout>
</ScrollView>
我使用了这段代码,效果很好:
https://discourse.nativescript.org/t/how-to-detect-if-component-is-in-screen-view-is-visible/1148/4
我可以更改“ng-template”中“StackLayout”的背景颜色。
但我无法访问我的自定义组件变量来修改他的行为。
例如,如果显示“my-custom-component”,我想更改“aCard”属性中传递的“card”对象中的属性“isShown”。
谢谢大家 :)
EDIT1:“isShown”是我用于此测试的自定义变量。我的想法是在 afterScroll 函数中计算可见的卡片是什么,并将参数传递给 aCard 以改变他的行为。
解决方案
您可以在滚动事件时找到 ScrollView 中每个子组件的位置,将其与垂直偏移量进行比较可以让您知道该组件是否真的在屏幕上可见。
这是一个游乐场示例。当您向下/向上滚动时,可见组件的背景颜色将变为绿色,否则变为红色。
onScroll(event: EventData) {
const scrollView = <ScrollView>event.object,
verticalOffset = scrollView.verticalOffset,
height = scrollView.getActualSize().height,
visibleRange = verticalOffset + height,
container = <StackLayout>this.container.nativeElement;
let index = 0;
container.eachLayoutChild((childView) => {
const locationY = childView.getLocationRelativeTo(container).y;
this.cards[index].isShown = locationY >= verticalOffset && locationY <= visibleRange
index += 1;
});
}
推荐阅读
- php - bash:php:仅在 VSC 中找不到命令
- c++ - 如果我用自定义 new 运算符的成员新建一个类会发生什么?
- python - 如何从 AJAX 将 mySQL 数据从服务器端显示为 HTML
- python - 如何使用 python 从 Street View Static API 渲染请求的图像?
- c++ - 如何在构造函数中初始化struct的动态数组?
- unity3d - 当对象不为空时,Unity 中的 NullReferenceException 问题
- python-3.x - 如何将函数应用于知道每个单元格位置的熊猫矩阵?
- tensorflow - 如何理解transformer中的masked multi-head attention
- excel - 如何在excel中的一列数据中搜索特定数字?
- c - 尝试使用 fscanf 将 .txt 文件中的字符串读取到字符串数组中,使用整数而不是字符串。段错误