首页 > 解决方案 > Nativscript 平台特定模板不起作用

问题描述

在 Nativescript 5.0 中为 Android 和 iOS 构建应用程序。出于某种原因,and 标签似乎无法正常工作,或者我可能做错了。

<StackLayout>
<android>
    <ActionBar class="header" flat="true">
        <StackLayout orientation="vertical">
            <app-eon-colors-top></app-eon-colors-top>
            <GridLayout columns="auto, *, auto, auto" rows="2*">
                <Label class="title" col="0" text="{{title}}" verticalAlignment="center"></Label>
                <Label class="icon fa-solid" col="2" text="&#xf2f5;" verticalAlignment="center"></Label>
                <Label class="logout fa-solid" col="3" row="0" text="Logga ut" verticalAlignment="center" (tap)="logout()"></Label>
            </GridLayout>
        </StackLayout>
    </ActionBar>
</android>
<ios>
    <ActionBar class="header" flat="false">
        <StackLayout orientation="horizontal">
            <Label class="title" text="{{title}}"></Label>
        </StackLayout>
        <ActionItem ios.position="right">
            <StackLayout orientation="horizontal">
                <Label class="icon fa-solid" text="&#xf2f5;"></Label>
                <Label class="logout fa-solid" ios.position="right" text="Logga ut" (tap)="logout()"></Label>
            </StackLayout>
        </ActionItem>
    </ActionBar>
</ios>
</StackLayout>

在 android 上运行此模板时,它只使用 ios 块中的代码,但在 ios 上它似乎工作正常。

标签: nativescriptangular2-nativescript

解决方案


这是编写平台特定 XML 的 NativeScript Core 方式。使用 Angular,你可以使用指令,有一个Github issue讨论了这个问题,还提供了示例代码来在你的项目中实现这个特定于平台的指令。

平台特定的结构指令

import { Directive, ViewContainerRef, TemplateRef, Inject } from "@angular/core";
import { DEVICE } from "nativescript-angular/platform-providers";

import { Device, platformNames } from "platform";

@Directive({
    selector: "[appIfAndroid]"
})
export class IfAndroidDirective {
    constructor( @Inject(DEVICE) device: Device, container: ViewContainerRef, templateRef: TemplateRef<Object>) {
        if (device.os === platformNames.android) {
            container.createEmbeddedView(templateRef);
        }
    }
}

@Directive({
    selector: "[appIfIos]"
})
export class IfIosDirective {
    constructor( @Inject(DEVICE) device: Device, container: ViewContainerRef, templateRef: TemplateRef<Object>) {
        if (device.os === platformNames.ios) {
            container.createEmbeddedView(templateRef);
        }
    }
}

一旦你在你的模块中导入这个指令,你就可以在任何标签上使用*appIfAndroid/ 。*appIfIos


推荐阅读