gpt4 book ai didi

objective-c - 看不到新的 subview

转载 作者:行者123 更新时间:2023-12-03 17:39:03 24 4
gpt4 key购买 nike

我想做的就是向 NSWindow 实例的内容 View 添加一个新 View 。当我执行以下操作时,我看不到新 View (它应该是黑色并占据整个窗口)。我做错了什么?

(响应按钮点击而完成)

NSRect frameRect = [self.window frame];
frameRect.origin = NSZeroPoint;

NSView *view = [[NSView alloc] initWithFrame:frameRect];
view.wantsLayer = YES;
view.layer.backgroundColor = [NSColor blackColor].CGColor;

[self.window.contentView addSubview:view];

最佳答案

我在 ViewController 内设置了一个带有按钮的简单项目,并收到了访问 self.window 的警告。使用 self.view.window 时,警告消失,您提供的代码按预期工作。

更新代码

NSRect frameRect = [self.view.window frame];
frameRect.origin = NSZeroPoint;

NSView *view = [[NSView alloc] initWithFrame:frameRect];
view.wantsLayer = YES;
view.layer.backgroundColor = [NSColor blackColor].CGColor;

[self.view.window.contentView addSubview:view];

更新

假设您使用 WindowController 实例以编程方式添加按钮,您的代码将按预期工作。

@implementation WindowController

- (void)windowDidLoad
{
[super windowDidLoad];

CGRect buttonRect = CGRectMake(self.window.frame.size.width / 2 - 50,
self.window.frame.size.height / 2,
100,
50);
NSButton *button = [[NSButton alloc] initWithFrame:NSRectFromCGRect(buttonRect)];
[button setTitle: @"Click me!"];
[button setTarget:self];
[button setAction:@selector(buttonPressed)];
[self.window.contentView addSubview:button];
}

- (void)buttonPressed
{
NSRect frameRect = [self.window frame];
frameRect.origin = NSZeroPoint;

NSView *view = [[NSView alloc] initWithFrame:frameRect];
view.wantsLayer = YES;
view.layer.backgroundColor = [NSColor blackColor].CGColor;

[self.window.contentView addSubview:view];
}

NSViewController 的实例没有 window 的属性 - 只有 NSWindowController 有一个属性。

关于objective-c - 看不到新的 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com