3 UI 组件-Column 容器介绍
本文将带您学习 ArkUI 框架中的重要线性布局容器——Column,其用于实现垂直方向的布局。
3.1 主轴与纵轴概念
在 Column 容器中:
- 主轴是竖直方向,用于排列子组件。
- 纵轴是水平方向,用于设置子组件的对齐方式。
- 这与 Row 容器的方向定义正好相反。
3.2 Column 容器的定义与属性
3.2.1 Column 容器的定义
Column 容器的定义方式与 Row 类似,支持通过参数 space 设置子组件的间距:
Column({ space: 10 }) {
Text("Child 1")
Text("Child 2")
}
3.2.2 Column 容器的属性
alignItems(设置子组件在纵轴上的对齐方式):
- HorizontalAlign.Start:起始端对齐。
- HorizontalAlign.Center(默认值):居中对齐。
- HorizontalAlign.End:末端对齐。
justifyContent(设置子组件在主轴上的分布方式):
- 适用的值与 Row 容器一致,如 FlexAlign.Center、FlexAlign.End 等。
3.3 Column 容器的使用示例
// xxx.ets
@Entry
@Component
struct ColumnExample {
build() {
Column({ space: 5 }) {
// 设置子元素垂直方向间距为5
Text('space').width('90%')
Column({ space: 5 }) {
Column().width('100%').height(30).backgroundColor(0xAFEEEE)
Column().width('100%').height(30).backgroundColor(0x00FFFF)
}.width('90%').height(100).border({ width: 1 })
// 设置子元素水平方向对齐方式
Text('alignItems(Start)').width('90%')
Column() {
Column().width('50%').height(30).backgroundColor(0xAFEEEE)
Column().width('50%').height(30).backgroundColor(0x00FFFF)
}.alignItems(HorizontalAlign.Start).width('90%').border({ width: 1 })
Text('alignItems(End)').width('90%')
Column() {
Column().width('50%').height(30).backgroundColor(0xAFEEEE)
Column().width('50%').height(30).backgroundColor(0x00FFFF)
}.alignItems(HorizontalAlign.End).width('90%').border({ width: 1 })
Text('alignItems(Center)').width('90%')
Column() {
Column().width('50%').height(30).backgroundColor(0xAFEEEE)
Column().width('50%').height(30).backgroundColor(0x00FFFF)
}.alignItems(HorizontalAlign.Center).width('90%').border({ width: 1 })
// 设置子元素垂直方向的对齐方式
Text('justifyContent(Center)').width('90%')
Column() {
Column().width('90%').height(30).backgroundColor(0xAFEEEE)
Column().width('90%').height(30).backgroundColor(0x00FFFF)
}.height(100).border({ width: 1 }).justifyContent(FlexAlign.Center)
Text('justifyContent(End)').width('90%')
Column() {
Column().width('90%').height(30).backgroundColor(0xAFEEEE)
Column().width('90%').height(30).backgroundColor(0x00FFFF)
}.height(100).border({ width: 1 }).justifyContent(FlexAlign.End)
}.width('100%').padding({ top: 5 })
}
}
在这个示例中,以上代码通过ArkUI框架的Column组件展示了垂直布局的使用,并在其中嵌套了多个Text和Column组件。代码首先设置了外层Column的子元素垂直方向间距为5。接着,通过不同的Column嵌套展示了alignItems和justifyContent属性的效果。alignItems用于设置子元素在水平方向上的对齐方式,分别展示了Start(左对齐)、End(右对齐)和Center(居中对齐)的效果。而justifyContent则用于设置子元素在垂直方向上的对齐方式,展示了Center(居中对齐)和End(底部对齐)的效果。每个Column组件都设置了不同的宽度、高度、背景色和边框,以清晰地展示布局效果。整体布局宽度设置为100%,并添加了顶部内边距,使布局更加美观。
3.4 总结
Column容器是ArkUI开发框架中一种非常重要的布局方式。通过合理使用其属性和子组件的排列方式,我们可以轻松地构建出各种美观且实用的用户界面。