cocos creator UI開發技巧

爲了充分發揮可視化的優勢,我打算把所有用到的界面全部寫好在UI中,只不過隱藏起來,這時就設計到一個問題,組件何時被加載呢?

如:創建和加入房間,這些界面先都是隱藏起來。我把這個隱藏的界面分爲了2類:我不想拖動節點到組件上。

如:Tip爲例子那麼我就寫一個Tip組件類,這個Tip節點開始是隱藏的,那麼這個Tip組件類何時被加載呢?

最初的組件以場景來命名如:Hall組件,那麼我這個Tip組件時在Hall中添加,還是直接拖到Tip上?

我建議:

直接把Tip組件拖到Tip節點上。 因爲這個Tip可能在5個界面中使用。所以Tip組件拖到Tip節點上更好。

使用


        	let tip = cc.find("Canvas/Tip");
        
        	let self = this;
        	self.schedule(function () {
            	tip.getComponent("Tip").show("hello 你好啊!" + Math.random() * 100);
            	self.scheduleOnce(function () {
                	tip.getComponent("Tip").hide();
           		}, 1)
        	}, 5);

Tip組件


			tip.getInstance().showTip("歡迎你");

			cc.Class({
    			extends: cc.Component,

    			properties: {},

    			onLoad: function () {
        			let nodeLabel = this.node.getChildByName("TipLabel");
        			this.label = nodeLabel.getComponent(cc.Label);
    			},

    			// LIFE-CYCLE CALLBACKS:
    			show: function (str) {
    				// 組件被添加,此時先調用onLoad。 再調用
        			this.node.active = true;


        			this.label.string = str;
    			},

    			hide: function () {
        			this.node.active = false;
    			}
			});


	

注意:

 onLoad: function () {

        cc.log("CreateRoom onLoad Called0000");
        let nodeLabel = cc.find("Canvas/TestLabel");
        this.lbl = nodeLabel.getComponent(cc.Label);
    },

    showStr: function (str) {
        cc.log("CreateRoom showStr called11111", this.lbl);
        this.node.active = true;
        cc.log("CreateRoom showStr called222", this.lbl);
        this.lbl.string = str;
    },

其實這個調用順序是:1111   000   222,雖然cocos是單線程的,

因爲這個node.active被調用,看着是屬性,其實是有get和set方法,因此會調用onLoad.

因此對於隱藏的界面, 始終是對的。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章