用了CocosCreator也有一段时间,对ToggleGroup始终没有仔细的学习过,只停留在用过的水平。因此由于认识有限,因此觉得ToggleGroup对自定义支持得没那么好,这两天由于项目,再学习了一下,发现ToggleGroup的toggleItems属性有着很大的做用。node
ToggleGroup的toggle事件对checkmark做的仅仅是隐藏和显示,而对background节点着没有做用,若是有一天,咱们想要点击的时候checkmark显示,而background隐藏的话,就能够用到toggleItems。程序员
这里还有一个提示:当给toggleGroup动态增长toggle的时候,toggle组件的toggleGroup属性是ToggleGroup组件,而不是挂着ToggleGroup组件的节点。api
代码为:学习
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的子节点,可是总有例外,程序员不该该有这样不严谨的逻辑。this
而我我的对getChildByName这样的api有点恐惧,由于这样意味着会被束缚,这样一来节点和子节点的关系会被束缚,子节点的名字会被束缚,并且代码可读性不好。url
下面就写一个点击toggle的时候显示checkmark隐藏background的实例。component
代码很简单,并且写一遍后,还能够用在其余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) {
// },
});get