Ionic 2 - 动态更改状态栏的颜色



我正在尝试根据获取的参数在离子页面中更改状态栏颜色。

只有onDeviceReady()函数内的colorStatusBar变量显示为undefined

有人可以帮助我解决这个问题吗?

typeColor: string;
colorStatusBar: string;
constructor(public navCtrl: NavController, public navParams: NavParams, statusBar: StatusBar){
this.typeColor = this.navParams.get('type');
if(this.typeColor == "value1"){
this.colorStatusBar = "#F44336";
}
if(this.typeColor == "value2"){
this.colorStatusBar = "#66BB6A";
}
if(this.typeColor == "value3"){
this.colorStatusBar = "#9E9E9E";
}
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(this.colorStatusBar) // undefined
statusBar.backgroundColorByHexString(this.colorStatusBar);
}
}

我只能让它按如下方式工作:

import { Component } from '@angular/core';
import { NavController, NavParams, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
...
typeColor: string;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public statusBar: StatusBar,
public platform: Platform){
this.typeColor = this.navParams.get('type');
this.platform.ready().then(() => {
if(this.typeColor == "value1"){
statusBar.backgroundColorByHexString("#F44336");
}
if(this.typeColor == "value2"){
statusBar.backgroundColorByHexString("#66BB6A");
}
if(this.typeColor == "value3"){
statusBar.backgroundColorByHexString("#9E9E9E");
}
})
}
...

你可以通过在ionViewDidLoad()内移动逻辑(在构造函数之后运行)并使用platform.ready()来确保Cordova已经启动来做到这一点:

ionViewDidLoad() {
this.typeColor = this.navParams.get('type');
this.platform.ready().then(() => {
if(this.typeColor == "value1"){
this.statusBar.backgroundColorByHexString("#F44336");
}
if(this.typeColor == "value2"){
this.statusBar.backgroundColorByHexString("#66BB6A");
}
if(this.typeColor == "value3"){
this.statusBar.backgroundColorByHexString(#9E9E9E");
}
}
}

在这种情况下,您的构造函数将更改为以下内容:

constructor(public navCtrl: NavController, public navParams: NavParams, public statusBar: StatusBar, public platform: Platfom){
// empty :), but notice the dependency injection of Platform
}

不要忘记在顶部导入Platform

import { Platform } from 'ionic-angular';

为了使您的特定示例正常工作,您需要确保从父页面调用此当前页面传入参数type

因此,在父页面中(您尚未共享代码),您需要具有如下所示的内容:

export class ParentPage {
constructor(public navCtrl: NavController) {
}
pushPage(){
// push another page onto the navigation stack
// causing the nav controller to transition to the new page
// optional data can also be passed to the pushed page.
this.navCtrl.push(MyStackOverflowSharedPage, {
type: "value2"
});
}
}

有关这方面的更多信息,请阅读有关NavController的文档。

相关内容

  • 没有找到相关文章

最新更新