概述
栅格布局是一种通用的辅助定位工具,对移动设备的界面设计有较好的借鉴作用。主要优势包括:
GridRow为栅格容器组件,需与栅格子组件GridCol在栅格布局场景中联合使用。
布局的总列数
GridRow中通过columns设置栅格布局的总列数。
- columns默认值为12,即在未设置columns时,任何断点下,栅格布局被分成12列。
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown,Color.Red, Color.Orange, Color.Yellow, Color.Green];
...
GridRow() {
ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
GridCol() {
Row() {
Text(`${index}`)
}.width('100%').height('50')
}.backgroundColor(item)
})
}
- 当columns为自定义值,栅格布局在任何尺寸设备下都被分为columns列。下面分别设置栅格布局列数为4和8,子元素默认占一列,效果如下:
class CurrTmp{
currentBp: string = 'unknown';
set(val:string){
this.currentBp = val
}
}
let BorderWH:Record<string,Color|number> = { 'color': Color.Blue, 'width': 2 }
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown];
@State currentBp: string = 'unknown';
...
Row() {
GridRow({ columns: 4 }) {
ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
GridCol() {
Row() {
Text(`${index}`)
}.width('100%').height('50')
}.backgroundColor(item)
})
}
.width('100%').height('100%')
.onBreakpointChange((breakpoint:string) => {
let CurrSet:CurrTmp = new CurrTmp()
CurrSet.set(breakpoint)
})
}
.height(160)
.border(BorderWH)
.width('90%')
Row() {
GridRow({ columns: 8 }) {
ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
GridCol() {
Row() {
Text(`${index}`)
}.width('100%').height('50')
}.backgroundColor(item)
})
}
.width('100%').height('100%')
.onBreakpointChange((breakpoint:string) => {
let CurrSet:CurrTmp = new CurrTmp()
CurrSet.set(breakpoint)
})
}
.height(160)
.border(BorderWH)
.width('90%')
- 当columns类型为GridRowColumnOption时,支持下面六种不同尺寸(xs, sm, md, lg, xl, xxl)设备的总列数设置,各个尺寸下数值可不同。
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]
GridRow({ columns: { sm: 4, md: 8 }, breakpoints: { value: ['200vp', '300vp', '400vp', '500vp', '600vp'] } }) {
ForEach(this.bgColors, (item:Color, index?:number|undefined) => {
GridCol() {
Row() {
Text(`${index}`)
}.width('100%').height('50')
}.backgroundColor(item)
})
}
若只设置sm, md的栅格总列数,则较小的尺寸使用默认columns值12,较大的尺寸使用前一个尺寸的columns。这里只设置sm:4, md:8,则较小尺寸的xs:12,较大尺寸的参照md的设置,lg:8, xl:8, xxl:8
排列方向
栅格布局中,可以通过设置GridRow的direction属性来指定栅格子组件在栅格容器中的排列方向。该属性可以设置为GridRowDirection.Row(从左往右排列)或GridRowDirection.RowReverse(从右往左排列),以满足不同的布局需求。通过合理的direction属性设置,可以使得页面布局更加灵活和符合设计要求。
-
子组件默认从左往右排列。
GridRow({ direction: GridRowDirection.Row }){} -
子组件从右往左排列。
GridRow({ direction: GridRowDirection.RowReverse }){}
子组件间距
GridRow中通过gutter属性设置子元素在水平和垂直方向的间距。
-
当gutter类型为number时,同时设置栅格子组件间水平和垂直方向边距且相等。下例中,设置子组件水平与垂直方向距离相邻元素的间距为10。
GridRow({ gutter: 10 }){} -
当gutter类型为GutterOption时,单独设置栅格子组件水平垂直边距,x属性为水平方向间距,y为垂直方向间距。
GridRow({ gutter: { x: 20, y: 50 } }){}