1

In CocosBuilder, I have a custom class named TextInput used for user input, then I want add a max_length value to limit the length of user input.

It looks like below:

enter image description here

But when I run, I got the following error:

Cocos2d: Unexpected property: 'max_length'!

I tried to add int max_length; into TextInput.h. But nothing changed.

Here is my relative code.

TextInput.h

#ifndef __CrossKaiser__TextInput__
#define __CrossKaiser__TextInput__

#include "cocos2d.h"
#include "cocos-ext.h"
using namespace cocos2d;
using namespace cocos2d::extension;

class TextInput : public CCTextFieldTTF
{
public:
    CREATE_FUNC(TextInput);

    TextInput();
    virtual ~TextInput();

    virtual bool init();
    virtual void onEnter();
    virtual void insertText(const char * text, int len);
    virtual void deleteBackward();
    int max_length;

};
#endif 

TextInputLoader.h

#ifndef __CrossKaiser__TextInputLoader__
#define __CrossKaiser__TextInputLoader__

#include "TextInput.h"

/* Forward declaration. */
class CCBReader;
class TextInputLoader : public cocos2d::extension::CCLabelTTFLoader{
public:
    CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(TextInputLoader, loader);

protected:
    CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(TextInput);
};

#endif

So my question is what is the correct way to use 'Custom Properties' feature?

4

1 回答 1

0

我通过首先查看Cocos2d: Unexpected property: 'max_length'!错误消息的来源来解决此问题。

它在CCNodeLoader.cpp

#define PROPERTY_TAG "tag"

void CCNodeLoader::onHandlePropTypeInteger(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, int pInteger, CCBReader * pCCBReader) {
    if(pPropertyName->compare(PROPERTY_TAG) == 0) {
        pNode->setTag(pInteger);
    } else {
        ASSERT_FAIL_UNEXPECTED_PROPERTY(pPropertyName);
    }
}

从这段代码中,我们可以看到它只处理“tag”属性,所有其他属性都会抛出一个断言。

所以我想我可以重写这个方法,我可以在其中处理我自己的新自定义属性。

所以我在我的添加了一个覆盖方法TextInputLoader.cpp

#define PROPERTY_MAX_LENGTH "max_length"

void TextInputLoader::onHandlePropTypeInteger(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, int pInteger, CCBReader * pCCBReader)
{
    if(pPropertyName->compare(PROPERTY_TAG) == 0) {
        pNode->setTag(pInteger);
    }
    else if (pPropertyName->compare(PROPERTY_MAX_LENGTH) == 0){
        ((TextInput*)pNode)->setMaxLength(pInteger);
    }
    else {
        ASSERT_FAIL_UNEXPECTED_PROPERTY(pPropertyName);
    }
}

然后我在我的添加一个属性TextInput.h

CC_SYNTHESIZE(unsigned int, m_max_length, MaxLength);

它确实奏效了。我的问题解决了。

顺便说一句,这里我只覆盖onHandlePropTypeInteger处理整数。

如果有人想要其他类型的自定义属性,他可以重写匹配的方法CCNodeLoader.cpp,例如onHandlePropTypeStringonHandlePropTypeFloat等等。

于 2013-03-11T07:08:58.117 回答