目录

如何使用layoutWeight属性设置子元素尺寸权重

问题现象

如何使子组件按一定比例在父容器中进行尺寸分配?

背景知识

layoutWeight(value: number | string):设置组件的布局权重,使组件在父容器(Row/Column/Flex)的主轴方向按照权重分配尺寸。

解决方案

通过layoutWeight属性动态调整子元素尺寸占比的核心容器,适用于需要灵活布局的场景,下列方案以Row、Column为例,分别展示水平和竖直方向上layoutWeight的分配方法。

常见FAQ

Q:如何指定组件到屏幕边缘的距离。例如:Row容器中存在左侧Text,右侧TextInput两个子组件,要求左侧Text组件宽度固定,右侧TextInput宽度自适应,并且Text组件距离左边屏幕边缘和TextInput组件距离右侧屏幕边缘的距离均为16vp。

A:将Row组件的宽度设为屏幕宽度,左右内边距为16vp,Text设为固定宽度,TextInput添加layoutWeight属性即可。

示例代码如下:

@Entry
@Component
struct Index3 {
  controller: TextInputController = new TextInputController();


  build() {
    Row({ space: 16 }) {
      Text('示例文本')
        .textAlign(TextAlign.Center)
        .backgroundColor('#F1F3F5')
        .borderRadius(20)
        .height(40)
        .width(80)
        .font({ size: 16, weight: 500 })
        .fontColor('#182431');


      TextInput({ placeholder: 'input your word...', controller: this.controller })
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
        .caretColor(Color.Blue)
        .layoutWeight(1);
    }
    .padding({ left: 16, right: 16 })
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center);
  };
}