How to inherit ui button class

I want to inherit Button class, but i get error, why?

MyButton::MyButton() : Button()
{
    
}

MyButton* MyButton::create()
{
    auto button = new MyButton();
    if (button) 
    {
        button->autorelease();
        return button;
    }
    CC_SAFE_DELETE(button);
    return nullptr;
}

Hi @vitek

Try this:

CustomButton.h

#include "cocos2d.h"
#include "ui/CocosGUI.h"
using namespace cocos2d;

class CustomButton : public ui::Button
{
public:
    CREATE_FUNC(CustomButton);

private:
    bool init() override; 
};

CustomButton.cpp

#include "CustomButton.h"

bool CustomButton::init()
{
    if (ui::Button::init())
    {
        // HERE YOUR CUSTOM CODE
        return true;
    }
    else
        return false;
}

Class usage:

auto button = CustomButton::create();
// likely here you set position and other properties
addChild(button); 

Bye

3 Likes