简体   繁体   English

以编程方式添加CCButton

[英]Add CCButton programmatically

I am trying to adding CCButton in my Scene. 我试图在我的场景中添加CCButton I am using Sprite builder.Here is my code. 我正在使用Sprite Builder。这是我的代码。

CCButton *btnTest = [[CCButton alloc]initWithTitle:@"BNB test"];
    [btnTest.label setName:@"Test"];
    btnTest.position = ccp(150.0f, 150.0f);

    [self addChild:btnTest];

It's not showing on the scene. 它没有在现场显示。 What may be the reason? 可能是什么原因?

try this way,i used it for back button ,below code it work fine: 尝试这种方式,我将其用于后退按钮,下面的代码工作正常:

CCButton *backButton = [CCButton buttonWithTitle:@"[ Back ]" fontName:@"Verdana-Bold" fontSize:18.0f];
backButton.positionType = CCPositionTypeNormalized;
backButton.position = ccp(0.95f, 0.95f); // Top Right of screen
[backButton setTarget:self selector:@selector(BackClicked:)];
[self addChild:backButton];

may it will help you... 可能会帮助您...

Happy coding... :) 快乐的编码... :)

The interface on CCButton was a bit not smooth IMHO so I wrote a category. CCButton上的界面有点不流畅,恕我直言,所以我写了一个类别。

@implementation CCButton (additions)
+(id)buttonWithImagenamed:(NSString*)imagename block:(void(^)(id sender))block {
    CCSpriteFrame* spriteframe = [CCSpriteFrame frameWithImageNamed:imagename];
    NSAssert(spriteframe != nil, @"nil spriteframe for imagename: %@", imagename);
    CCButton* button = [CCButton buttonWithTitle:@"" spriteFrame:spriteframe];
    button.block = block;
    return button;
}
@end

This needs to be emphasized: "imagename" must be relative, so if you put it into a folder like "graphics/myimage.png", you need to specify @"graphics/myimage.png" in code. 需要强调的是:“ imagename”必须是相对的,因此,如果将其放入“ graphics / myimage.png”之类的文件夹中,则需要在代码中指定@"graphics/myimage.png" Only @"myimage.png" will NOT work in this case. 在这种情况下,只有@"myimage.png"不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM