ArkUI 学习之尺寸设置:layoutWeight(对子组件进行重新布局)
一、layoutWeight概述
在鸿蒙开发中,每个布局组件都可以设置layoutWeight属性。该属性是一个浮点数值,用于表示组件在布局中的相对权重。具体而言,layoutWeight属性决定了组件在布局中所占用的空间大小。设置的layoutWeight值越大,组件所占用的空间也就越大。相反,值越小,组件所占用的空间也就越小。
二、layoutWeight用法
layoutWeight(value: number | string)
🔊:对子组件进行重新布局。
参数:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
value | number | string | 是 |
父容器尺寸确定时,设置了layoutWeight属性的子元素与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,表示自适应占满剩余空间。 默认值:0 !!!说明: 可选值为大于等于0的数字,或者可以转换为数字的字符串。 如果容器中有子元素设置了layoutWeight属性,且设置的属性值大于0,则所有子元素不会再基于flexShrink和flexGrow布局。 |
示例:
@Entry @Component struct TestIndex { build() { Column() { Row() { Text('1/3') .backgroundColor(Color.Pink) .textAlign(TextAlign.Center) .size({ width: '30%', height: 110 }) Text('2/3') .backgroundColor(Color.Green) .textAlign(TextAlign.Center) .size({ width: '30%', height: 110 }) Text('no') .backgroundColor(Color.Yellow) .textAlign(TextAlign.Center) .size({ width: '10%', height: 110 }) } .backgroundColor(Color.Gray) .size({ width: '100%', height: 140 }) Divider().height(10) Row() { // 权重1,占主轴剩余空间1/3 Text('1/3') .backgroundColor(Color.Pink) .textAlign(TextAlign.Center) .size({ width: '30%', height: 110 }) .layoutWeight(1) // 权重2,占主轴剩余空间2/3 Text('2/3') .backgroundColor(Color.Green) .textAlign(TextAlign.Center) .size({ width: '30%', height: 110 }) .layoutWeight(2) // 未设置,组件按照自身尺寸渲染 Text('no') .backgroundColor(Color.Yellow) .textAlign(TextAlign.Center) .size({ width: '10%', height: 110 }) } .backgroundColor(Color.Black) .size({ width: '100%', height: 140 }) } } }