Ionic 更换主题风格方案

需求

最近涉及到的一个需求是——用户可更换页面风格,因此,查了一些资料后,写一下Ionic更换主题方案

方案

动态改变根标签类名,比如亮色风格时,class="light",比如暗色风格时,class="dark"

步骤

1.在 src/theme 文件夹下,新建两种不同风格
这里写图片描述

light.theme.scss
这里写图片描述

dark.theme.scss
这里写图片描述

2.在切换事件发生时,动态改变类名,因此,我们需要先写一个服务,用于初始化值接收传入的新值返回值

① 执行命令,创建setting服务
ionic g provider settings

② setting.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {BehaviorSubject} from "rxjs/Rx";

@Injectable()
export class SettingsProvider {

  private theme:BehaviorSubject<String>;

  constructor() {
    //默认初始值
    this.theme = new BehaviorSubject('dark-theme');
  }

  setActiveTheme(val){
    //新值
    this.theme.next(val);
  }

  getActiveTheme() {
    //观察
    return this.theme.asObservable();
  }
}

BehaviorSubject:继承自subject,发射observable数据

3.在页面中注入服务

home.html

<ion-content padding>
  <p text-center>I shine at night and glow at day.</p>
  <button ion-button full icon-left (click)="toggleAppTheme()">
    <ion-icon  name="bulb"></ion-icon>Toggle Theme
  </button>
</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {SettingsProvider} from "../../providers/settings/settings";

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  selectedTheme:String;

  constructor(public navCtrl: NavController,
              private settings:SettingsProvider) {
    //订阅可观察者对象
    this.settings.getActiveTheme().subscribe(val=> this.selectedTheme = val);
  }

  toggleAppTheme() {
    //切换事件发生时
    if (this.selectedTheme === 'dark-theme') {
      this.settings.setActiveTheme('light-theme');
    } else {
      this.settings.setActiveTheme('dark-theme');
    }
  }

}

4.同时,在根目录文件中注入服务,从而动态更换根标签类名

app.html

<ion-nav [root]="rootPage" [class]="selectedTheme"></ion-nav>
<!--绑定class名-->

app.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
import {SettingsProvider} from "../providers/settings/settings";
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;
  selectedTheme: String;

  constructor(platform: Platform,
              statusBar: StatusBar,
              splashScreen: SplashScreen,
              private settings:SettingsProvider) {
    this.settings.getActiveTheme().subscribe(val=> this.selectedTheme = val)
  }
}

5.效果图
这里写图片描述

参考:
dynamic-theming

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值