首页 > 解决方案 > Nativescript:如何在网格弹性框中使标签不超过其容器的宽度?

问题描述

我正在使用 NativeScript 6.4.1 和 Angular 8 编写应用程序。

在我的应用程序的主页上,我需要一个按钮列表,按钮下方有一个标签。

我希望包含按钮的容器和文本的宽度相同。如果文本太长,它将进入下一行,而不是扩大父容器的大小。

我曾尝试为此目的使用 FlexboxLayout,但我注意到父容器只是扩展: https ://play.nativescript.org/?template=play-ng&id=jbpqMk&v=5

我想我的布局也需要一些灵活性;也许有能力配置它的 2 或 3 列。

使用 GridLayout 会更好吗?

这是一个代码片段:

主页.html

<FlexboxLayout backgroundColor="pink" flexWrap="wrap" justifyContent="center">
    <ns-home-button *ngFor="let n of list" name="{{ n.name }}"></ns-home-button>
</FlexboxLayout>

期望的结果:

在此处输入图像描述

当前结果:

在此处输入图像描述

标签: cssangularlayoutflexboxnativescript

解决方案


有趣的是,您在演示中显示的单元格已根据您的流程规范正确对齐。使用 aGridLayout可能的,但不是很理想。需要计算和指定它的GridLayout所有行,这很烦人,而且它还会强制它的子级适应它,而不是基于子级(如FlexboxLayoutor StackLayout)进行扩展。

相反,只需在每个项目上设置一个宽度。最简单的两种方法是包装每个元素:

<FlexboxLayout backgroundColor="pink" flexWrap="wrap" justifyContent="center">
    <StackLayout width="33%" *ngFor="let n of list">
        <ns-home-button name="{{ n.name }}"></ns-home-button>
    </StackLayout>
</FlexboxLayout>

或通过修改组件规格:

<FlexboxLayout backgroundColor="pink" flexWrap="wrap" justifyContent="center">
    <ns-home-button width="33%" *ngFor="let n of list" name="{{ n.name }}"></ns-home-button>
</FlexboxLayout>
    @Input() width: string;
<FlexboxLayout [width]="width" ...>
    ...
</FlexboxLayout>

推荐阅读