我正在使用 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;
}
但是文本域没有出现,它在场景下面。有人知道问题是什么以及如何解决吗?
最佳答案
开始工作了。
必须将必要的 View 设置为 Layer-Backed Views。尝试在 Nib 中这样做,但对我不起作用。所以我用代码做到了。
- (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 设置为 subview ,而是设置为 SKView
的同级 View 。然后通过 setWantsLayer
将 UI 设置为 Layer-Backed。
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];
}
希望这对正在遵循我的步骤的其他人有所帮助。
关于objective-c - 如何在 SKScene 上添加 NSTextField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23181688/