如何在单独的 .XIB 文件中使用 Sheet window 显示 NSAlert?

How to show NSAlert using Sheet window in separate .XIB files?

我有一个执行任务的按钮,如果在此过程中发生错误,则会使用 NSAlert 显示警告 "Sheet window" 此刻我在一个项目中使用多个 .XIB 文件,我无法在这些文件(.XIB)中显示 "Sheet window" 有什么办法可以做到这一点吗? 提前致谢!

on clickedButton:sender

try
--some code here...

on error errorMsg
           set alert to current application's NSAlert's alloc's init()
           tell alert
               its setMessageText:"This is an ERROR"
               its setInformativeText: "Error: " & errorMsg
               its setAlertStyle:2
               its beginSheetModalForWindow:theWindow modalDelegate:me didEndSelector:(missing value) contextInfo:(missing value)
               end tell
            end try
end clickedButton:

如果您没有 window 来打开 sheet,您将需要 运行 正常的警报对话框。您可以使用 NSApp's mainWindow() 测试 window,如果没有 missing value,则执行 alert's runModal() 或 sheet,具体取决于结果:

use framework "Cocoa"
use scripting additions

property theWindow : missing value -- this will be the main window...
property sheetOrNot : true -- ... or not, depending on this flag

on run -- this lets the example run from the Script Editor if you forget the main thread thing
    my performSelectorOnMainThread:"doWindow" withObject:(missing value) waitUntilDone:true
    my performSelectorOnMainThread:"doAlert" withObject:(missing value) waitUntilDone:true
end run

on doWindow() -- create a window to play with
    set theWindow to current application's NSWindow's alloc's initWithContentRect:{{200, 400}, {400, 200}} styleMask:7 backing:(current application's NSBackingStoreBuffered) defer:true
    set theWindow's releasedWhenClosed to true
    if sheetOrNot then tell theWindow to makeKeyAndOrderFront:me
end doWindow

on doAlert() -- show the alert
    try
        --some code here...
        error "oops" -- ...that went badly
    on error errorMsg
        set alert to current application's NSAlert's alloc's init()
        tell alert
            its setMessageText:"This is an ERROR"
            its setInformativeText:("Error: " & errorMsg)
            its setAlertStyle:2
            if current application's NSApp's mainWindow() is not missing value then
                its beginSheetModalForWindow:theWindow modalDelegate:me didEndSelector:(missing value) contextInfo:(missing value)
            else -- no window, so do a normal modal dialog
                its runModal()
            end if
        end tell
    end try
end doAlert