鸿蒙应用开发中,Navigation和NavDestination的标题设置为居中

默认情况下,Navigation和NavDestination的标题都在左侧,并且没有原生接口直接设置标题居中。

在Navigation中,要设置居中,那么title属性要使用CustomBuilder,示例如下:

@Entry
@Component
struct Index {
......

  @Builder
  navigationTitle() {
    Row() {
      Text('主页面').fontSize(22).fontWeight(2)
      // x设置为0,width设置为100%,这样Row的宽度就是Navigation的TitleBar的宽度
    }.position({ x: 0 }).width('100%').justifyContent(FlexAlign.Center)
  }

  build() {
    Navigation() {
......
      // title属性使用CustomBuilder
    }.title(this.navigationTitle)
    .titleMode(this.navigationTitleMode)
  }
}

效果如下:

NavDestination的设置方法相同。

完整示例如下:


@Component
struct Page01 {
  pathStack: NavPathStack | undefined = undefined;

  @Builder
  navDestinationTitle() {
    Row() {
      Text('主页面').fontSize(22).fontWeight(2)
      // x设置为0,width设置为100%,这样Row的宽度就是Navigation的TitleBar的宽度
    }.position({ x: 0 }).width('100%').justifyContent(FlexAlign.Center)
  }

  build() {
    NavDestination() {
      Button(`pop`).width('80%').margin({ top: 10, bottom: 10 })
        .onClick(() => {
          this.pathStack?.pop();
        })
      // title属性使用CustomBuilder
    }.title(this.navDestinationTitle)
    .onReady((context: NavDestinationContext) => {
      this.pathStack = context.pathStack;
    })
  }
}

@Entry
@Component
struct Index {
  pathStack: NavPathStack = new NavPathStack();
  @State navigationTitleMode: NavigationTitleMode = NavigationTitleMode.Free;

  @Builder
  navigationTitle() {
    Row() {
      Text('主页面').fontSize(22).fontWeight(2)
      // x设置为0,width设置为100%,这样Row的宽度就是Navigation的TitleBar的宽度
    }.position({ x: 0 }).width('100%').justifyContent(FlexAlign.Center)
  }

  @Builder
  pagesMap(name: string) {
    if (name == 'Page01') {
      Page01()
    }
  }

  build() {
    Navigation(this.pathStack) {
      Column() {
        Button('切换导航标题模式').width('80%').margin({ top: 10, bottom: 10 })
          .onClick(() => {
            if (this.navigationTitleMode == NavigationTitleMode.Free) {
              this.navigationTitleMode = NavigationTitleMode.Full;
            } else if (this.navigationTitleMode == NavigationTitleMode.Full) {
              this.navigationTitleMode = NavigationTitleMode.Mini;
            } else if (this.navigationTitleMode == NavigationTitleMode.Mini) {
              this.navigationTitleMode = NavigationTitleMode.Free;
            }
          })
        Button('push Page01').width('80%').margin({ top: 10, bottom: 10 })
          .onClick(() => {
            this.pathStack.pushPath({ name: 'Page01' });
          })
      }.width('100%').height('100%')
      // title属性使用CustomBuilder
    }.title(this.navigationTitle)
    .titleMode(this.navigationTitleMode)
    .navDestination(this.pagesMap)
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值