【发布时间】:2011-12-30 21:07:41
【问题描述】:
在 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 的一部分,它是应用程序中呈现的第一个场景,如果这很重要的话。我在这里做错了什么?谢谢!
编辑:我可以确认按钮被添加到 windows 子视图中,因为 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: 无效吗?因为我宁愿不创建大量自动释放的对象,也因为我有一些 UIButton 子类在我使用 buttonWithType: 方法时不会显示。
编辑 3 (解决方案):
使用buttonWithType:以外的任何东西都不起作用的原因是如果你不使用那个方法来创建按钮,按钮的背景颜色是没有设置的,默认是clearColor。使用[button setBackgroundColor:[UIColor redColor]] 或任何其他颜色可以解决问题。此外,如果使用像 this one 这样的自定义按钮类,如果按钮未连接到笔尖,您可能需要手动调用 [button awakeFromNib]。
【问题讨论】:
-
在使用 [UIButton buttonWithType:....] 方法之前,我也无法显示按钮。奇怪。
-
查看我的编辑,我发现了问题。
标签: iphone uikit cocos2d-iphone uibutton