【问题标题】:Determine If component is visible in the screen确定组件是否在屏幕中可见
【发布时间】:2019-01-24 09:54:51
【问题描述】:

我使用 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>

我使用了这个 sn-p 的代码,效果很好:

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”属性。

谢谢大家:)

编辑1: “isShown”是我用于此测试的自定义变量。我的想法是在 afterScroll 函数中计算可见的卡片是什么,并将参数传递给 aCard 以改变他的行为。

【问题讨论】:

  • 相信你说的是原生android视图的isShown属性。在这种情况下,您的组件本身已经具有该值,所以请问您为什么要在 aCard 中传递它?
  • 不,“isShown”是我用于此测试的自定义变量。我的想法是在 afterScroll 函数中计算可见的卡片是什么,并将参数传递给 aCard 以改变他的行为。可以使用android的本机属性吗?怎么样?
  • 我认为如果视图可见或隐藏,则返回“isShown”,而不是在屏幕中可见时返回

标签: nativescript visibility show-hide angular2-nativescript nativescript-angular


【解决方案1】:

当滚动事件发生时,您可以在 ScrollView 中找到每个子组件的位置,将其与垂直偏移量进行比较可以让您知道该组件是否真的在屏幕上可见。

Here is a Playground example。当您向下/向上滚动时,可见组件的背景颜色将变为绿色,否则变为红色。

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;
    });
}

【讨论】:

    【解决方案2】:

    您需要更新您的allList 对象,因为NgForOf 是可绑定的,它会更新卡片并反映在您的my-custom-component 的[acard] 中

    在您必须使用相对高度的滚动事件中,您需要一个唯一变量来标识显示的组件并更改allList 中该索引的属性。

    我创建了一个示例 playgrod here,如果滚动高度大于 300,我将自定义组件 Label 的文本更改为 isShown。我更改标签名称的方式是,您可以在 @ 中有一个布尔变量987654326@ 改变你的逻辑来改变stackLayout的背景颜色。如果您想更新游乐场,请告诉我。

    【讨论】:

    • 但是你随意给出了“300”的度量,你还没有计算出卡片显示的是什么并找到了相对索引。
    • 正如您所提到的,您可以更改背景颜色,您的问题给我的印象是您正在寻找如何在自定义组件中传递变量的想法。
    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多