ionic 的 tabs 组件默认图标更换方式可以通过自定义图标样式来替换。自定义图标可以是图标字体库,也可以是png图标等。

一、编写样式

在 tabs.scss 文件(组件作用域),或者全局app.scss覆盖都行。下边是菜单覆盖代码:

page-tabs {
  .tabbar > .tab-button {
    min-height: 4.9rem;
  }
  .ion-tab-base {
      width: 2.2rem;
      background-size: cover;
      background-position: center;
  }
  $tabImageName: 'home' 'lesson' 'bell' 'me';
  @for $i from 1 to 5 {
    //for ios
    .ion-ios-tab-#{nth($tabImageName, $i)} {
      @extend .ion-tab-base;
      content: url("../../assets/icon/tab-#{nth($tabImageName, $i)}1.png");
    }
    .ion-ios-tab-#{nth($tabImageName, $i)}-outline {
      @extend .ion-tab-base;
      content: url("../../assets/icon/tab-#{nth($tabImageName, $i)}0.png");
    }
    // for android
    .tabs-md .tab-button[aria-selected=true] {
      .ion-md-tab-#{nth($tabImageName, $i)} {
        @extend .ion-tab-base;
        content: url("../../assets/icon/tab-#{nth($tabImageName, $i)}1.png");
      }
    }
    .tabs-md .tab-button[aria-selected=false] {
      .ion-md-tab-#{nth($tabImageName, $i)} {
        @extend .ion-tab-base;
        content: url("../../assets/icon/tab-#{nth($tabImageName, $i)}0.png");
      }
    }
  }
}

二、scss 语法说明

1. 数组

$tabImageName: 'home' 'lesson' 'bell' 'me';

2. 循环

@for $i from 1 to 5
这是循环4次

3. 取数组中元素

#{nth($tabImageName, $i)}
通过取出循环中的每个元素,定义每个图标的样式,这个就是scss预编译样式的好处,省去重复的工作和重复的代码。

4. 样式区分

从样式代码可以看出,定义了两份代码,一份是 ios 的 ion-ios- 前缀,一份是 android 版本的 ion-md- 与 .tabs-md 前缀,还有这个是ionic对不同平台有不同的样式,如果了解一看就明白了。-outline 为 ios 未选中样式,[aria-selected=false] 为 android 未选中样式。

然后在 html 里边,修改 tabIcon 为样式中定义的图标即可。(上边样式图标统一加了 tab-前缀,为了和自带图标区分开来)

三、资源文件

图标路径放在 src/assets/icon 下,如图
Ionic4 自定义tabs菜单图标

四、更换前和更换后对比

更换前:

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="首页" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="课程" tabIcon="list-box"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="消息" tabIcon="notifications-outline"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="我的" tabIcon="person"></ion-tab>
</ion-tabs>

Ionic4 自定义tabs菜单图标
更换后:

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="首页" tabIcon="tab-home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="课程" tabIcon="tab-lesson"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="消息" tabIcon="tab-bell"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="我的" tabIcon="tab-me"></ion-tab>
</ion-tabs>

Ionic4 自定义tabs菜单图标

相关文章: