首页 > 解决方案 > 在 NativeScript 布局中居中和右/左对齐项目

问题描述

在 NativeScript 应用程序的上下文中,我一直在努力寻找一种有效的、非 hacky 的方法来完成看起来很简单的事情:将一个项目放在布局的中心,将另一个项目一直放在右边或左边的布局 - 类似于这个问题中的图像:居中和右对齐 flexbox 元素。这些项目都应该在一行中,因为它们在那里。(我已经查看了这些解决方案,但我不想添加伪元素,而且很多 CSS 无法与 NativeScript 一起使用。)是否有某种干净、规范的方法可以使用默认布局?如果这不够“具体”,假设我有这样的场景:

<SomeLayout>
  <Label text="Center me"></Label>
  <Label text="Pull me to the right"></Label>
</SomeLayout>

标签的文本属性描述了我正在寻找的内容。请测试任何建议或确保它们有效。

标签: nativescript

解决方案


您可以通过对两个标签应用相同的行号来使用horizontalAlignmentwith GridLayout

<GridLayout rows="auto" columns="*">
  <Label row="0" horizontalAlignment="center" text="Center me" class="center"></Label>
  <Label row="0" horizontalAlignment="right" text="Pull me to the right" class="right"></Label>
</GridLayout>

您还可以horizontalAlignment使用属性从 CSS设置horizontal-align属性。

.center{
    horizontal-align:center;
}
.right{
    horizontal-align:right;
}

主要技巧是您必须为标签提供相同的行号,以便它们相互重叠。


推荐阅读