默认情况下,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)
  }
}
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐