相对布局RelativeContainer,当子组件设置了margin时,居中效果不符合预期

希望Text和TextInput在竖直方向可以在同一水平线上对齐,当给Text组件设置margin-top后,两个组件没有对齐,Text组件偏下。

HarmonyOS
2024-02-20 14:57:33
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
truemichael

给Text组件设置margin时,可以给上下两个方向设置相同的margin,此时两个组件可以在水平方向对齐,因为相对布局RelativeContainer设置锚点时,是以组件占据的所有空间计算的,包括margin和padding,如果只设置margintop,锚点设为VerticalAlign.Center,实际锚点位置在Text组件中心点偏上。

示例代码

@Entry 
@Component 
struct relativeLayoutExample { 
  build() { 
    RelativeContainer() { 
      Text('宽度') 
        .fontSize(12) 
        .padding({ 
          left: 20, 
          right: 12 
        }) 
        .fontColor('#222630') 
        .margin({ 
          top: 20, 
          bottom: 20 // 这里如果只设置margin-top,会导致后面TextInput组件在竖直方向上的锚点位置在Text组件中心偏上 
        }) 
        .alignRules({ 
          left: { anchor: '__container__', align: HorizontalAlign.Center }, 
          top: { anchor: '__container__', align: VerticalAlign.Top } 
        }) 
        .id('width-text') 
 
      TextInput() 
        .backgroundColor('#F7F7F8') 
        .borderRadius(8) 
        .height(32) 
        .width(56) 
        .fontSize(14) 
        .maxLength(4) 
        .fontColor(Color.Black) 
        .type(InputType.Number) 
        .onChange(() => { 
 
        }) 
        .alignRules({ 
          center: { anchor: 'width-text', align: VerticalAlign.Center }, 
          left: { anchor: 'width-text', align: HorizontalAlign.End } 
        }) 
        .id('width-edit') 
    } 
    .width('100%') 
    .height(300) 
    .border({ width: 2, color: "#6699FF" }) 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
分享
微博
QQ
微信
回复
2024-02-20 20:08:29


相关问题
HarmonyOS BlendMode显示效果不符合预期
810浏览 • 1回复 待解决
点击事件冒泡不符合预期
1358浏览 • 1回复 待解决
RichText组件font标签size属性不符合预期
2605浏览 • 1回复 待解决
HarmonyOS 不符合UI组件语法
947浏览 • 1回复 待解决
相对布局RelativeContainer
2043浏览 • 1回复 待解决
元服务UI不符合设计规范?
274浏览 • 0回复 待解决
HarmonyOS 3DES的key长度不符合
660浏览 • 1回复 待解决
HarmonyOS Text添加动画效果预期不符
768浏览 • 1回复 待解决