目标C - 如何在窗口中放置关闭按钮?

时间:2023-01-20 17:03:58

I'm having a problem on putting a close button in my window in objective C, I have created the button, but I don't know what the method I need to call to close the window, I have done this:

我在目标C中在我的窗口中放置一个关闭按钮时遇到问题,我创建了按钮,但我不知道关闭窗口需要调用的方法是什么,我已经这样做了:

    -(void)awakeFromNib{

//Create a button
    NSRect frame = NSMakeRect(350, 10, 100, 50);
    NSButton *btn = [[NSButton alloc]initWithFrame:frame];
    [btn setButtonType:NSMomentaryPushInButton];
    [btn setBezelStyle:NSRoundedBezelStyle];
    [btn setTitle:@"Close"];
    [btn setTarget:self];
    [btn setAction:@selector(closeWindow)];
    [view addSubview:btn];



}


-(void)closeWindow{}

I don't know what to put in close window method

我不知道在关闭窗口方法中放什么

3 个解决方案

#1


2  

You can close the current window by using something along these lines:

您可以使用以下行中的内容关闭当前窗口:

NSWindow *window = [[NSApplication sharedApplication] keyWindow];
[window close];

However, this does not actively simulate a user closing a window, since it does not call delegate methods, nor does it highlight the close button. You may want to use this instead:

但是,这不会主动模拟用户关闭窗口,因为它不会调用委托方法,也不会突出显示关闭按钮。你可能想要使用它:

NSWindow *window = [[NSApplication sharedApplication] keyWindow];
[window performClose:sender];

In that case, you'd probably want pass your button as the sender. You can receive the button in your closeWindow method as an object to make things simple.

在这种情况下,您可能希望将按钮作为发件人传递。您可以在closeWindow方法中接收按钮作为对象,以简化操作。

#2


0  

If your doing it from your NSWindowController subclass, just call [self close].

如果您从NSWindowController子类中执行此操作,只需调用[self close]。

#3


0  

If you touch a view to current this view, you can use removeFromSuperview. Just simple add [self removeFromSuperview];

如果触摸视图以显示当前视图,则可以使用removeFromSuperview。只需简单添加[self removeFromSuperview];

#1


2  

You can close the current window by using something along these lines:

您可以使用以下行中的内容关闭当前窗口:

NSWindow *window = [[NSApplication sharedApplication] keyWindow];
[window close];

However, this does not actively simulate a user closing a window, since it does not call delegate methods, nor does it highlight the close button. You may want to use this instead:

但是,这不会主动模拟用户关闭窗口,因为它不会调用委托方法,也不会突出显示关闭按钮。你可能想要使用它:

NSWindow *window = [[NSApplication sharedApplication] keyWindow];
[window performClose:sender];

In that case, you'd probably want pass your button as the sender. You can receive the button in your closeWindow method as an object to make things simple.

在这种情况下,您可能希望将按钮作为发件人传递。您可以在closeWindow方法中接收按钮作为对象,以简化操作。

#2


0  

If your doing it from your NSWindowController subclass, just call [self close].

如果您从NSWindowController子类中执行此操作,只需调用[self close]。

#3


0  

If you touch a view to current this view, you can use removeFromSuperview. Just simple add [self removeFromSuperview];

如果触摸视图以显示当前视图,则可以使用removeFromSuperview。只需简单添加[self removeFromSuperview];