前言:如果在遊戲中使用開關組件的話,一般會使用Toggle。可是總有一些開關的兩態是不重疊,圖片會有一大一小。這個時候還使用Toggle的話,就會出現問題。那可以使用將要介紹的自定義控制ToggleOne。組件的功能跟Toggle一樣,只是在選中與未選中時,只顯示對應的圖片,另一張會隱藏。文章最後會給出一個Demo給大家參考。
效果
未選中狀態
選中狀態
###代碼實現
代碼很簡單,主要是查看Toggle源碼,來進行實現的。感興趣的朋友可以自己查看源碼。
cc.Class({
extends: cc.Component,
properties: {
isChecked: {
default: true,
tooltip: CC_DEV && 'i18n:COMPONENT.toggle.isChecked',
notify: function () {
this._updateCheckMark();
}
},
background: cc.Sprite,
checkMark: cc.Sprite,
/**
* !#en If Button is clicked, it will trigger event's handler
* !#zh 按鈕的點擊事件列表。
* @property {Component.EventHandler[]} clickEvents
*/
checkEvents: {
default: [],
type: cc.Component.EventHandler,
tooltip: CC_DEV && 'i18n:COMPONENT.button.click_events',
}
},
onLoad() {
this._updateCheckMark();
},
onEnable() {
this.node.on(cc.Node.EventType.TOUCH_END, this.toggle, this);
},
onDisable() {
this.node.off(cc.Node.EventType.TOUCH_END, this.toggle, this);
},
toggle(event) {
console.log('ToggleOne');
this.isChecked = !this.isChecked;
this._updateCheckMark();
if (this.checkEvents) {
cc.Component.EventHandler.emitEvents(this.checkEvents, this, this.isChecked);
}
},
setChecked(isChecked) {
this.isChecked = isChecked;
this._updateCheckMark();
},
_updateCheckMark() {
if (this.checkMark) {
this.checkMark.node.active = !!this.isChecked;
}
if (this.background) {
this.background.node.active = !!!this.isChecked;
}
},
});
###最後
Demo地址。喜歡就動動手指點喜歡,關注我吧。我會不定時更新Cocos Creator教程哦~