4.1布局-grid布局
// Grid布局的基本使用: 规则的行列布局中非常常见, 3行4列
Grid() {
ForEach([1,2,3,4,5,6,7,8,9,10,11,12], () => {
GridItem() {
Column() {
}
.width('100%')
.height('100%')
.backgroundColor(Color.Green)
.border({ width: 1 })
}
})
}
.columnsTemplate('1fr 1fr 1fr 1fr')
.rowsTemplate('1fr 1fr 1fr')
.columnsGap(5)
.rowsGap(5)
.width('100%')
.height(500)
.backgroundColor(Color.Pink)
4.2 Flex布局
// Flex默认主轴水平往右,交叉轴垂直往下 → Row
// 1. 主轴方向
// direction: FlexDirection.Row / Column
// 2. 主轴对齐方式
// justifyContent: FlexAlign.SpaceAround
// 3. 交叉轴对齐方式
// alignItems: ItemAlign.Stretch / Start / Center / End
// 单行或者单列的情况,优先还是使用线性布局(本质基于Flex设计的,且还做了性能优化)
// Flex布局:伸缩布局。当子盒子的总和溢出父盒子,默认进行压缩显示。
// 4. 换行 wrap
// FlexWrap.Wrap 换行
// FlexWrap.NoWrap 不换行
Flex({
direction: FlexDirection.Column,
justifyContent: FlexAlign.SpaceBetween,
alignItems: ItemAlign.Start,
wrap: FlexWrap.Wrap
}) {
Text()
.width(80).height(80)
.backgroundColor(Color.Pink)
.border({ width: 1, color: Color.Blue })
Text()
.width(80).height(80)
.backgroundColor(Color.Pink)
.border({ width: 1, color: Color.Blue })
Text()
.width(80).height(80)
.backgroundColor(Color.Pink)
.border({ width: 1, color: Color.Blue })
}
.width('100%')
.height(600)
.backgroundColor('#5f9a5c')
4.3 层叠布局
// 层叠布局
Stack({
alignContent: Alignment.Bottom
}) {
Text('大儿子')
.width(250)
.height(250)
.backgroundColor(Color.Green)
.zIndex(3)
Text('二儿子')
.width(150)
.height(150)
.backgroundColor(Color.Orange)
.zIndex(4)
Text('三儿子')
.width(50)
.height(50)
.backgroundColor(Color.Yellow)
.zIndex(5)
}
.width(300)
.height(600)
.backgroundColor(Color.Pink)