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) {

    // },
});


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值