我正在使用Sprite Kit创建游戏,想要在场景上添加文本字段。这是代码:
@interface MKMainMenuScene ()
//...
@property (nonatomic) NSTextField *field;
@end
@implementation MKMainMenuScene
- (void)didMoveToView:(SKView *)view
{
[super didMoveToView:view];
[self.view addSubview:_field];
}
- (id)initWithSize:(CGSize)size
{
if (self == [super initWithSize:size])
{
//...
_field = [[NSTextField alloc] initWithFrame:
NSMakeRect(self.frame.size.width / 2, self.frame.size.height / 2 + 20,
100, 40)];
[_field setBackgroundColor:[NSColor whiteColor]];
[_field setStringValue:@"Enter smth"];
}
return self;
}
但是文本字段没有出现,它在场景下。有人知道问题是什么以及如何解决?
答案 0 :(得分:1)
搞定了。
必须将必要的视图设置为图层支持的视图。试图在笔尖中做这件事对我来说不起作用。所以我在代码中做到了。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
/* Insert Label. FOR TESTING, may remove */
NSTextField *label = [[NSTextField alloc] initWithFrame:NSMakeRect(50, 50, 300, 300)];
[label setStringValue:@"Hello All"];
[label setTextColor:[NSColor whiteColor]];
[label setBackgroundColor:[NSColor redColor]];
[label setFont:[NSFont fontWithName:@"Helvetica" size:20]];
[[self.window contentView] addSubview:label];
/* SET LAYER BACK VIEW
* This is the one line code to make it work.
*/
[self.window.contentView setWantsLayer:YES];
}
的更新:强>
以上代码会导致SCNView
或SKView
冻结或出现问题。要解决此问题,请不要将UI设置为子视图,而应将其设置为SKView
的兄弟。然后将用户界面设置为由setWantsLayer
进行分层支持。
Window
-> Content NSView
-> SKView/SCNView
-> NSTextField <-- Layer-Backed
代码:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
/* Insert Label. FOR TESTING, may remove */
NSTextField *label = [[NSTextField alloc] initWithFrame:NSMakeRect(50, 50, 300, 300)];
// . . . .
[[self.window contentView] addSubview:label];
/* UPDATE */
[label setWantsLayer:YES];
}
希望这可以帮助那些正在遵循我的步骤的人。
答案 1 :(得分:0)
试试这个:
- (void)didMoveToView:(SKView *)view
{
[super didMoveToView:view];
[view addSubview:_field];
}