CocosCreator的ToggleGroup组件使用

用了CocosCreator也有一段时间,对ToggleGroup始终没有仔细的学习过,只停留在用过的水平。所以因为认识有限,所以以为ToggleGroup对自定义支持得没那么好,这两天因为项目,再学习了一下,发现ToggleGroup的toggleItems属性有着很大的作用。

ToggleGroup的toggle事件对checkmark作的仅仅是隐藏和显示,而对background节点着没有作用,如果有一天,我们想要点击的时候checkmark显示,而background隐藏的话,就可以用到toggleItems。

这里还有一个提示:当给toggleGroup动态增加toggle的时候,toggle组件的toggleGroup属性是ToggleGroup组件,而不是挂着ToggleGroup组件的节点。

代码为:


var node = cc.instantiate(this.prefab);
node.getComponent(cc.Toggle).toggleGroup = this.getComponent(cc.ToggleGroup);
node.parent = this.node;
当然如果,想要获取toggleGroup的toggle节点,也可以用getChildByName或者类似的api来获取,但是这种方法并不全面,因为虽然toggle节点基本上都是toggleGroup的子节点,但是总有例外,程序员不应该有这样不严谨的逻辑。

而我个人对getChildByName这样的api有点恐惧,因为这样意味着会被束缚,这样一来节点和子节点的关系会被束缚,子节点的名字会被束缚,而且代码可读性很差。

下面就写一个点击toggle的时候显示checkmark隐藏background的实例。

代码很简单,而且写一遍后,还可以用在其他toggle上面,复用性很好。


cc.Class({
extends: cc.Component,

properties: {
// foo: {
// default: null, // The default value will be used only when the component attaching
// to a node for the first time
// url: cc.Texture2D, // optional, default is typeof default
// serializable: true, // optional, default is true
// visible: true, // optional, default is true
// displayName: 'Foo', // optional
// readonly: false, // optional, default is false
// },
// ...
},

// use this for initialization
onLoad: function () {
this.node.on("toggle", this.onToggleChangeSpriteFrame, this);
},

onToggleChangeSpriteFrame : function() {
var toggle = this.getComponent(cc.Toggle);
var items = toggle.toggleGroup.toggleItems;
for(var i = 0; i < items.length; i++) {
items[i].target.active = true;
}
toggle.target.active = !toggle.isChecked;
},

// called every frame, uncomment this function to activate update callback
// update: function (dt) {

// },
});

原文地址:https://www.cnblogs.com/luorende/p/9816908.html