我有两个不同的窗口控制器。首先是自定义面板窗口控制器,另一个是主窗口控制器。在面板窗口中有一个面板窗口,该面板上有按钮。点击这些按钮,我发布的通知如下:
In PanelWindowController:
-(IBAction)okAndCancelButtonClicked:(id)sender
{
[self postNotification:sender];
}
-(void)postNotification:(id)sender
{
if([sender tag]!=2){
[[self window] endSheet:self.panel returnCode:NSModalResponseCancel];
[self.panel orderOut:self];
}
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:[sender tag]],@"value",nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"PanelButtonClickedNotification" object:self userInfo:dict];
}
现在,在我的主窗口控制器中,我正在尝试在NSBeginAlertSheet
selector
的{{1}}中打开addObserver
。以下是我的主窗口控制器的NSNotificationCenter
方法中的addObserver
selector
声明:
init
MainWindowController
-(id) init{
..// some code here
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(okButtonClicked:) name:@"PanelButtonClickedNotification" object:[self panelClass]];
return self;
}
的实施如下:
okButtonClicked
当用户单击Panel上的No按钮时,应显示窗口上的警告。但警报从未显示过。我还尝试了- (void) okButtonClicked:(NSNotification*)notification
{
if ([[notification object] isEqualTo:[self panelClass]])
{
if([[[notification userInfo] objectForKey:@"value"] integerValue] == 1)
{
// Yes Button in the Panel is clicked
}
else if([[[notification userInfo] objectForKey:@"value"] integerValue] == 0)
{
// No Button in the Panel is clicked
NSBeginAlertSheet(@"Alert", @"Ok", nil, nil, [[self view] window], self,nil, nil,nil,@"Alert is being shown on window.");
}
}
}
和[NSApp keyWindow]
而不是[NSApp mainWindow]
。
并且,如果我独立于窗口运行警报,则会显示:
[[self view] window]
如果我在这里遗漏任何东西,请告诉我。
在收到通知后调用的任何方法中都不会显示警报。 PFA我的示例项目:https://www.dropbox.com/s/0xfe4bk17v9girj/PanelApplication.zip?dl=0
答案 0 :(得分:0)
这有点难以辨别,但我最好的猜测是,在okButtonClicked:函数中对通知作出反应的对象没有对窗口的(有效)引用。然后,警报不知道要显示的窗口。
如果您可以在通知对象中发送对窗口的引用,那么您应该能够获得所需窗口上显示的警报。
示例代码:
[[NSNotificationCenter defaultCenter] postNotificationName:@"PanelButtonClickedNotification" object:[self window]];
和
- (void) okButtonClicked:(NSNotification*)notification
{
NSBeginAlertSheet(@"Alert", @"Ok", nil, nil, [notification object], self,nil, nil,nil,@"Alert is being shown on window.");
}
这适用于我的测试项目。
答案 1 :(得分:0)
问题不在于通知,而是导致问题的面板: 我正在我的主窗口控制器中打开面板:
[[self window] beginSheet:self.panelClass.panel completionHandler:nil];
面板的关闭动作写在Panel窗口控制器中。由于这个原因,在主窗口上加载/卸载自定义面板后,没有显示NSBeginAlertSheet
。
因此,将以下代码从面板窗口控制器移动到主窗口控制器解决了这个问题:
[[self window] endSheet:self.panelClass.panel returnCode:NSModalResponseCancel];
[self.panelClass.panel orderOut:self];