将UIButtons添加到Cocos2d项目中

4
在Cocos2d中,我读到过这样的内容:
[[[[CCDirector sharedDirector] openGLView] window] addSubview:someButton];

将会向主窗口添加一个UIView:http://www.cocos2d-iphone.org/forum/topic/3588

但是在我的代码中,我有这个:

- (void)onEnterTransitionDidFinish {
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [[[[CCDirector sharedDirector] openGLView] window] addSubview:button];
}

但是没有按钮可见。如果这很重要,这种方法是CCLayerColor的一部分,它是应用程序中呈现的第一个场景。我在这里做错了什么?谢谢!

编辑:我可以确认按钮被添加到窗口子视图中,因为正在NSLogging。
[[[[[CCDirector sharedDirector] openGLView] window] subviews] count]

当我注释或取消注释addSubview行时,显示出不同。那么为什么按钮没有显示出来呢?

编辑2:

感谢@Marine,我发现我的问题是我声明按钮的方式;使用buttonWithType:解决了这个问题,因为这段代码可以工作:

UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(100, 100, 100, 100)];
[[[[CCDirector sharedDirector] openGLView] window] addSubview:button];

有人能解释一下为什么使用这个类方法有效,而使用initWithFrame:则无效吗?因为我不想创建很多自动释放的对象,而且当我使用buttonWithType:方法时,有些UIButton子类不会显示出来。
编辑3(解决方案):
使用buttonWithType:以外的任何方法都不起作用的原因是,如果您不使用该方法创建按钮,则按钮的背景颜色未设置,默认值为clearColor。使用[button setBackgroundColor:[UIColor redColor]]或任何其他颜色都可以解决此问题。此外,如果使用像这样的自定义按钮类,则可能需要手动调用[button awakeFromNib],如果按钮没有连接到nib文件。

2
直到我使用了[UIButton buttonWithType:...]方法,我也无法显示按钮。很奇怪。 - jmosesman
看我的修改,我找出了问题。 - eric.mitchell
3个回答

1

我已经将问题的解决方案发布为问题的编辑。


哇塞,非常感谢!!!你不知道这对我有多大帮助。我刚开始学习Objective-C/iOS/Cocos2d开发,甚至不知道从哪里开始解决这个问题。谢谢你,你让我的一天变得美好了!!! - David T.
没问题。我很高兴能帮助你! - eric.mitchell

1

尝试下面的代码,它会帮助你的。

-(id) init 
{
    if((self = [super init])) 
    {
    UIView* glView = (UIView*) [[CCDirector sharedDirector] openGLView];        
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setFrame:CGRectMake(100, 100, 250, 250)];
    [btn addTarget:self action:@selector(actionper:) forControlEvents:UIControlEventTouchUpInside];
            [glView addSubview:btn];
    }
    return self;
}
-(void) actionper : (id) sender
{
    printf("\n Stuff of the Code on button Press");
}

0
尝试使用OpenGL窗口的bringsubviewtofront方法,将最近添加的按钮作为参数传递。还要确保您的按钮框架位于屏幕可见部分。尝试调整其位置。

作为另一个测试,尝试创建一个UIview并将按钮添加到其中,然后将UIview添加到OpenGL窗口中。 - bweberapps

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接