cocos2d-x3.x 弹出对话框的设计与实现

先定义一个类PopupLayer


代码PopupLayer.h


#ifndef __crossDT_PopupLayer__
#define __crossDT_PopupLayer__

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

class PopupLayer :public Layer
{
public:
	PopupLayer();
	~PopupLayer();
	virtual bool init();
	CREATE_FUNC(PopupLayer);

	//virtual void registerWithTouchDispatcher(void);
	bool onTouchBegan(Touch *touch, Event *unused_event);

	static PopupLayer * create(const char* backgroundImage);
	void setTitle(const char* title ,int fontsize=20);
	void setContentText(const char* text ,int fontsize=20 ,int padding=50 ,int paddintTop=100);
	void setCallbackFunc(Object* target, SEL_CallFuncN callfun);
	
	bool addButton(const char* normalImage, const char* selectedImage, const char* title, int tag=0);
	virtual void onEnter();
	virtual void onExit();

private:
	void buttonCallback(CCObject* pSender);

    // 文字内容两边的空白区
    int m_contentPadding;
    int m_contentPaddingTop;
    
    CCObject* m_callbackListener;
    SEL_CallFuncN m_callback;

    CC_SYNTHESIZE_RETAIN(Menu*, m__pMenu, MenuButton);
    CC_SYNTHESIZE_RETAIN(Sprite*, m__sfBackGround, SpriteBackGround);
    CC_SYNTHESIZE_RETAIN(Scale9Sprite*, m__s9BackGround, Sprite9BackGround);
    CC_SYNTHESIZE_RETAIN(LabelTTF*, m__ltTitle, LabelTitle);
    CC_SYNTHESIZE_RETAIN(LabelTTF*, m__ltContentText, LabelContentText);


};


#endif


PopupLayer.cpp里面的代码

#include "PopupLayer.h"

PopupLayer::PopupLayer():
m__pMenu(NULL)
, m_contentPadding(0)
, m_contentPaddingTop(0)
, m_callbackListener(NULL)
, m_callback(NULL)
, m__sfBackGround(NULL)
, m__s9BackGround(NULL)
, m__ltContentText(NULL)
, m__ltTitle(NULL)
{
    
}

PopupLayer::~PopupLayer(){
    CC_SAFE_RELEASE(m__pMenu);
    CC_SAFE_RELEASE(m__sfBackGround);
    CC_SAFE_RELEASE(m__ltContentText);
    CC_SAFE_RELEASE(m__ltTitle);
    CC_SAFE_RELEASE(m__s9BackGround);
}

bool PopupLayer::init(){
	if(!Layer::init()){
		return false;
	}
		this->setContentSize(CCSizeZero);
        
        // 初始化需要的 Menu
        CCMenu* menu = CCMenu::create();
        menu->setPosition(CCPointZero);
        setMenuButton(menu);
        
        setTouchEnabled(true);

	return true;
}

bool PopupLayer::onTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent){
    //
    CCLog("PopupLayer touch");
    return true;
}

PopupLayer* PopupLayer::create(const char *backgroundImage){
    PopupLayer* ml = PopupLayer::create();
    ml->setSpriteBackGround(CCSprite::create(backgroundImage));
    ml->setSprite9BackGround(Scale9Sprite::create(backgroundImage));
    return ml;
}

void PopupLayer::setTitle(const char *title, int fontsize){
    CCLabelTTF* ltfTitle = CCLabelTTF::create(title, "", fontsize);
    setLabelTitle(ltfTitle);
}

void PopupLayer::setContentText(const char *text, int fontsize, int padding, int paddingTop){
    CCLabelTTF* ltf = CCLabelTTF::create(text, "", fontsize);
    setLabelContentText(ltf);
    m_contentPadding = padding;
    m_contentPaddingTop = paddingTop;
}

void PopupLayer::setCallbackFunc(cocos2d::CCObject *target, SEL_CallFuncN callfun){
    m_callbackListener = target;
    m_callback = callfun;    
}


bool PopupLayer::addButton(const char *normalImage, const char *selectedImage, const char *title, int tag){
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    CCPoint pCenter = ccp(winSize.width / 2, winSize.height / 2);
    
    // 创建图片菜单按钮
    CCMenuItemImage* menuImage = CCMenuItemImage::create(normalImage, selectedImage, this, menu_selector(PopupLayer::buttonCallback));
    menuImage->setTag(tag);
    menuImage->setPosition(pCenter);
    
    // 添加文字说明并设置位置
    CCSize imenu = menuImage->getContentSize();
    CCLabelTTF* ttf = CCLabelTTF::create(title, "", 20);
    ttf->setColor(ccc3(0, 0, 0));
    ttf->setPosition(ccp(imenu.width / 2, imenu.height / 2));
    menuImage->addChild(ttf);
    
    getMenuButton()->addChild(menuImage);
    return true;
}

void PopupLayer::buttonCallback(cocos2d::CCObject *pSender){
    CCNode* node = dynamic_cast<CCNode*>(pSender);
    CCLog("touch tag: %d", node->getTag());
    if (m_callback && m_callbackListener){
        (m_callbackListener->*m_callback)(node);
    }
    this->removeFromParent();
}

void PopupLayer::onEnter(){
    CCLayer::onEnter();
    
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    CCPoint pCenter = ccp(winSize.width / 2, winSize.height / 2);
    
    CCSize contentSize;
    // 设定好参数,在运行时加载
    if (getContentSize().equals(CCSizeZero)) {
        getSpriteBackGround()->setPosition(ccp(winSize.width / 2, winSize.height / 2));
        this->addChild(getSpriteBackGround(), 0, 0);
        contentSize = getSpriteBackGround()->getTexture()->getContentSize();
    } else {
        Scale9Sprite *background = getSprite9BackGround();
        background->setContentSize(getContentSize());
        background->setPosition(ccp(winSize.width / 2, winSize.height / 2));
        this->addChild(background, 0, 0);
        contentSize = getContentSize();
    }
    
    
    // 添加按钮,并设置其位置
    this->addChild(getMenuButton());
    float btnWidth = contentSize.width / (getMenuButton()->getChildrenCount() + 1);
    
	Vector<Node*> vecArray = getMenuButton()->getChildren();
    CCObject* pObj = NULL;
    int i = 0;
	for(auto& e : vecArray){
		CCNode* node = dynamic_cast<CCNode*>(e);
		node->setPosition(Point(winSize.width/2 - contentSize.width/2+btnWidth*(i+1),winSize.height/2-contentSize.height/3));
		i++;
	}
  /*  CCARRAY_FOREACH(array, pObj){
        CCNode* node = dynamic_cast<CCNode*>(pObj);
        node->setPosition(ccp( winSize.width / 2 - contentSize.width / 2 + btnWidth * (i + 1), winSize.height / 2 - contentSize.height / 3));
        i++;
    }*/
    
    
    // 显示对话框标题
    if (getLabelTitle()){
        getLabelTitle()->setPosition(ccpAdd(pCenter, ccp(0, contentSize.height / 2 - 35.0f)));
        this->addChild(getLabelTitle());
    }
    
    // 显示文本内容
    if (getLabelContentText()){
        CCLabelTTF* ltf = getLabelContentText();
        ltf->setPosition(ccp(winSize.width / 2, winSize.height / 2));
        ltf->setDimensions(CCSizeMake(contentSize.width - m_contentPadding * 2, contentSize.height - m_contentPaddingTop));
        ltf->setHorizontalAlignment(kCCTextAlignmentLeft);
        this->addChild(ltf);
    }

    // 弹出效果
    CCAction* popupLayer = CCSequence::create(CCScaleTo::create(0.0, 0.0),
                                              CCScaleTo::create(0.06, 1.05),
                                              CCScaleTo::create(0.08, 0.95),
                                              CCScaleTo::create(0.08, 1.0), NULL);
    this->runAction(popupLayer);

}

void PopupLayer::onExit(){
    
    CCLog("popup on exit.");
    CCLayer::onExit();
}


在要引用的代码里面添加

#include "HelloWorldScene.h"
#include "PopupLayer.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
     CCSize winSize = CCDirector::sharedDirector()->getWinSize();
        CCPoint pointCenter = ccp(winSize.width / 2, winSize.height / 2);

        // 添加背景图片
      /*  CCSprite* background = CCSprite::create("HelloWorld.png");
        background->setPosition(pointCenter);
        background->setScale(1.5f);
        this->addChild(background);    */
        
        //popupLayer();
        
        
        // 添加菜单
        CCMenu* menu = CCMenu::create();
        
        CCMenuItemFont* menuItem = CCMenuItemFont::create("popup", this, menu_selector(HelloWorld::menuCallback));
		menuItem->setPosition(ccp(winSize.width/2, winSize.height/2));
        menuItem->setColor(ccc3(255, 0, 0));
        menu->addChild(menuItem);
        

        menu->setPosition(CCPointZero);
        this->addChild(menu);
   
    
    return true;
}


void HelloWorld::popupLayer(){
    // 定义一个弹出层,传入一张背景图
    PopupLayer* pl = PopupLayer::create("popuplayer/BackGround.png");
    // ContentSize 是可选的设置,可以不设置,如果设置把它当作 9 图缩放
    pl->setContentSize(CCSizeMake(400, 350));
    pl->setTitle("吾名一叶");
    pl->setContentText("娇兰傲梅世人赏,却少幽芬暗里藏。不看百花共争艳,独爱疏樱一枝香。", 20, 60, 250);
    // 设置回调函数,回调传回一个 CCNode 以获取 tag 判断点击的按钮
    // 这只是作为一种封装实现,如果使用 delegate 那就能够更灵活的控制参数了
    pl->setCallbackFunc(this, callfuncN_selector(HelloWorld::buttonCallback));
    // 添加按钮,设置图片,文字,tag 信息
    pl->addButton("popuplayer/pop_button.png", "popuplayer/pop_button.png", "确定", 0);
    pl->addButton("popuplayer/pop_button.png", "popuplayer/pop_button.png", "取消", 1);
    // 添加到当前层
    this->addChild(pl);
}

void HelloWorld::menuCallback(cocos2d::Object *pSender){
    popupLayer();
}

void HelloWorld::buttonCallback(cocos2d::Node *pNode){
    CCLog("button call back. tag: %d", pNode->getTag());
}


下面是网上转载的代码,那个里面是cocos2d-x2.x里面的代码,有一些修改

我们时常需要这么些功能,弹出一个层,给与用户一些提示,这也是一种模态窗口,在没有对当前对话框进行确认的时候,不能继续往下操作。在设计如此功能之时,怎么设计比较合理 ~ 是这篇文章要讨论的问题。一叶 不倾向于提供给一个完整的解决方案,给一堆源码。而会靠诉你如何根据你自己的需要去完善它,授人以鱼不如授人以渔 ~

功能分析

我们设计一个对话框,对话框上有几个按钮(个数可定制),当然有个标题,会让别人一眼看出它之功用,里面可以有些详细的提示文字,需要是模态窗口,而且窗口的大小可变,这样能够更好的适应不同的屏幕的大小。当然还有一个重要的功能,弹出效果 ~ 虽然从技术角度来说,实现起来并不难,或者说非常简单,但这会以一个很好的用户体验展示给用户。

为了使用方面,我将接口设计的尽量简洁,便于使用,如下所示,至于内部的实现,那就随意了,接口函数是暴露在外面的,给别人使用,所以根据需要首先将它定义好,会让你的实现步骤思路清晰 (本文所用到的源代码可以从  这里  获取):

class PopupLayer: public CCLayer{
public:
    PopupLayer();
    ~PopupLayer();

    virtual bool init();
    CREATE_FUNC(PopupLayer);

    // 需要重写触摸注册函数,重新给定触摸级别
    virtual void registerWithTouchDispatcher(void);
    // 重写触摸函数,永远返回 true ,屏蔽其它层,达到 “模态” 效果
    bool ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent);

    // 构架,并设置对话框背景图片
    static PopupLayer* create(const char* backgroundImage);

    // 它可以显示标题,并且设定显示文字大小
    void setTitle(const char* title, int fontsize = 20);
    // 文本内容,padding 为文字到对话框两边预留的距离,这是可控的,距上方的距离亦是如此
    void setContentText(const char* text, int fontsize = 20, int padding = 50, int paddintTop = 100);

    // 回调函数,当点击按钮后,我们关闭弹出层的同事,需要一个回调函数,以通知我们点击了哪个按钮(如果有多个)
    void setCallbackFunc(CCObject* target, SEL_CallFuncN callfun);

    // 为了添加按钮方面,封装了一个函数,传入些必要的参数
    bool addButton(const char* normalImage, const char* selectedImage, const char* title, int tag = 0);

    // 为了在显示层时之前的属性生效,选择在 onEnter 里动态展示
    virtual void onEnter();
    virtual void onExit();

};

从使用方面的角度来说,定义了以上函数,以供外部调用,完成基本的功能需求。当然还有些隐藏的函数,如 setContentSize。由此开始我们的下一步设计 ~

onEnter 动态组建弹出层

前文提到过,需要的模态窗口大小是可变的,通过 ContentSize 来获取,如果没有设置 ContentSize ,那么采取的方案是,窗口大小与传入图片一样大,反之,将窗口设定为指定大小。我们知道有很多类似于这样的属性设置修改等,对于完成这样一个功能来说,有两种方式。

其一, 实时设置,实时刷新 ,比如在 static PopupLayer* create(const char* gackgroundImage)  的实现里面,创建一个精灵,并设置好图片,添加到当前层,如果调用了  setContentSize  我们再在此方法获取精灵后去修改这个精灵的大小(很显然在本文,并没有实现 setContentSize 方法,但并不影响解说)。

其二, 保留属性,动态组建 。这样一种实现是在 static PopupLayer* create(const char* gackgroundImage)  方法内部,只保存图片的名称,而  setContentSize  也可以只专注于自己的工作即可。最后在一个适当的执行时期,根据以上两个参数,动态创建符合需求的精灵,而这个操作在 onEnter 里尤为合适。

再以一个当前用到的例子,来说明  实时刷新  与  动态组建  的区别。看到定义中有一个  addButton  的方法,它是为了可以在当前对话框中添加一个或者几个按钮,而添加几个?当然并不确定,但确定的是,它们的位置会随着按钮个数的不同而不同,如果一个按钮,将居中显示(一分为二),如果两个(三等份距离),如果是实时刷新,我们在每一次  addButton  方法里面创建一个新的按钮,还需要设置正确的位置,当然在设置新位置的时候,你需要去判断是否已经存在按钮,还需要修改q前面按钮的位置,可以预见,每添加一次,都需要去实时刷新之前设置过的值,如果代码逻辑简单还好,如果逻辑非常复杂,依赖属性之多,那么那将不好控制。如果使用  动态组建 ,在  addButton  方面里面我们只需要用一个集合(类似机制)来保存所有的按钮信息,仅此而已,然后在 onEnter 中,读取这些信息,以实时添加按钮至界面之中,而在运行到这里之时,属性基本已经确定了(这里是按钮个数)。只需计算一次各按钮的位置,这样的逻辑处理就相当清晰了 ~

可以说动态组建就一定比实时刷新要好么?当然不是。 一个采用实时刷新的例子: 在 Cocos2d-x 的 CCControl 的框架中,使用了实时刷新的解决方案,可以在很多地方看到类似  needsLayout()  这样的操作,在设定一个控件的属性之后,需要根据属性更新控件的布局等。

对于 实时刷新 与 动态组建 这两种方式,需要根据实际情况来选择,以简化我们的开发,而在文本中,基本是以动态组建的方式设计,因为在弹出层运行之时,所有的属性就已经确定,它没有必要再去根据属性实时刷新。

弹出层的触摸优先级,操作与显示相一致

-128  是一个有意义的数字,它是 CCMenu 的默认触摸级别,如果我们不使用自带的菜单项,那么对于触摸级别的问题就很好处理了,随便一个稍微大一点的值,即可。但是你需要自己写按钮处理的实现。当然使用 CCMenu 也是有好处的,它封装了非常好用的点击操作。为了简化开发,这里就基于以 CCMenu 作为对话框按钮的操作实现。那么我们的 弹出层 触摸级别改设置为多少?

在我们设定触摸级别时,请记住一句话, 操作与显示相一致 。此话何意?现在设想这样一种情况,我们为了屏蔽弹出层以外所有的层的操作,而将弹出层级别置为 -129 ,这样便保证了它是模态的了(一般而言,除了 CCMenu 的级别,用户自定义也无需这么大),但是如果当前弹出层上方还有其它的层(也可以是弹出层的父节点上方有其它层,如多层的 UI 设计),并且其上也有 CCMenu 按钮,那么就出现了显示在 弹出层上放层中的 CCMenu 按钮不能点击,这不科学!实际,在弹出层的 CCMenu 也不能点击,只是我们可以通过将弹出层的触摸消息传递给层中的 CCMenu 解决。所以设置为一味的追求最大的触摸优先级,并不可取,它不能很好的做到  操作与显示相一致 ,而优先级小于 CCMenu 并不能屏蔽下方的其它 CCMenu 操作,所以对于弹出层本身,它设置为 -128 是合理的,对于同样级别的这些元素来说(弹出层和CCMenu),能够做到,显示在最上方的优先处理。如果在弹出层上方还有层,是可以点击的,为什么不呢!而我们要做的是,通过逻辑控制,让弹出层节点,最后添加到场景的最上方。

对于  操作与显示相一致  的一个解决方案,可以参考一叶的另两篇文章, 多层 UI 触摸事件的轻量级设计 ,和  CCScrollView 实现帮助界面、关卡选择 。当然那里并没有用到 CCMenu,而是独立创建了一套规则。

回调函数的实现方案

由于我们使用了 CCMenu 作为按钮,所以完全可以将 CCMenu 的回调函数,当作参数传入进来,这样处理确实很简单,但是另一个问题,我门需要在事件处理完之后,关闭当前层,那这就不能仅仅如此了,需要进一步封装,将弹出层的按钮回调函数设置为内部实现,然后在 回调给它的上层,之后关闭对话框(关闭的操作由对话框层来完成),对于回调一般有两种方式,一种是  delegate  回调,这需要定义接口,由上层,继承实现接口,并把自己当作参数,传入弹出层,由弹出层调用 delegate 的接口方法实现,在 Cocos2d-x 里面很多地方用到此方式。而另一种则是 函数绑定,就像 CCMenu 那样的绑定函数。

在这里,一叶选择了后者,如果当前弹出层固定一个或者两个按钮,那么我将使用 delegate 来实现函数回调,它会使回调步骤更为清晰,但是,这里设计的是按钮个数可变,功能也不尽相同,使用回调函数,绑定 CCNode 参数,以其 tag 标示,点击的是哪个按钮,当然这里也并不是说使用那种方式是绝对的好坏。delegate 对参数传递来说,更为严谨。 void setCallbackFunc(CCObject* target, SEL_CallFuncN callfun);  的定义是类似 CCMenu 的回调机制,一个 CCNode 作为参数,其 tag 用以标示当前点击的是哪个按钮。

弹出层的调用

void Popup::popupLayer(){
    // 定义一个弹出层,传入一张背景图
    PopupLayer* pl = PopupLayer::create("popuplayer/BackGround.png");
    // ContentSize 是可选的设置,可以不设置,如果设置把它当作 9 图缩放
    pl->setContentSize(CCSizeMake(400, 350));
    pl->setTitle("吾名一叶");
    pl->setContentText("娇兰傲梅世人赏,却少幽芬暗里藏。不看百花共争艳,独爱疏樱一枝香。", 20, 60, 250);
    // 设置回调函数,回调传回一个 CCNode 以获取 tag 判断点击的按钮
    // 这只是作为一种封装实现,如果使用 delegate 那就能够更灵活的控制参数了
    pl->setCallbackFunc(this, callfuncN_selector(Popup::buttonCallback));
    // 添加按钮,设置图片,文字,tag 信息
    pl->addButton("popuplayer/pop_button.png", "popuplayer/pop_button.png", "确定", 0);
    pl->addButton("popuplayer/pop_button.png", "popuplayer/pop_button.png", "取消", 1);
    // 添加到当前层
    this->addChild(pl);
}

void Popup::buttonCallback(cocos2d::CCNode *pNode){
    // 打印 tag 0, 确定,1 ,取消
    CCLog("button call back. tag: %d", pNode->getTag());
}

// 弹出效果 关键代码,当前层直执行这个动作
CCAction* popupLayer = CCSequence::create(CCScaleTo::create(0.0, 0.0),
                                          CCScaleTo::create(0.06, 1.05),
                                          CCScaleTo::create(0.08, 0.95),
                                          CCScaleTo::create(0.08, 1.0), NULL);

这里一张截图,其中 popup 按钮是个 CCMenu,弹出层中两个按钮也是 CCMenu,而层本身的触摸优先级别也是 -128 ,都是同级,那就依我所言,操作与显示相一致,唯一要注意的是逻辑的控制,什么时候弹出层,由哪个节点弹出层(一般由场景基层来负责),以保证它显示在最上方。

Cocos2d-x 弹出对话框的设计与实现

通过以上的讨论实践,完成了对话框的基本模型,它实现了以下功能:

  • 一个可以弹出的对话框实现
  • 模态窗口的实现(需要逻辑的控制)
  • 多按钮的支持,位置自适应,提供回调函数
  • 提供标题和内容设置
  • 支持  九图  ,控制适应弹出框大小

当然还有许多其它并没有照顾到的功能,或者不完善的地方,这就需要用户自己扩展,定制了,如,这样一个层,至少应该是单例的,任何时候只应该存在一个,可以用单例模式实现,对于弹出层的内容方面,这里只有标题和内容,并且标题位置固定,按钮的位置还可以更灵活的设置等。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值