首页 > 解决方案 > 如何使用 NSAlert 获取单击按钮的返回值

问题描述

我正在使用以下内容:

tell current application's NSAlert's alloc's init()
  its setMessageText:"Alert test"
  its setInformativeText:"This is a test"
  its setAlertStyle:2
  its setShowsSuppressionButton:true
  its addButtonWithTitle:"Cancel"
  its addButtonWithTitle:"Replace"
  its beginSheetModalForWindow:theWindow modalDelegate:me didEndSelector:(missing value) contextInfo:(missing value)
end tell

我想知道如何获得单击按钮的值,包括“抑制按钮”。提前谢谢!

标签: applescript-objc

解决方案


使用Myriad HelpersNSAlert+MyriadHelpers中的类别,您可以使用该方法。使用 Xcode 的默认 AppleScript 应用程序项目并向其中添加类别 .h 和 .m 文件,示例如下:showOverWithSuppress:calling:

property suppressed : false

on applicationWillFinishLaunching:aNotification
    tell current application's NSUserDefaults's standardUserDefaults
        its registerDefaults:{SuppressAlert:suppressed}
        set my suppressed to its objectForKey:"SuppressAlert"
    end tell
    set state to ""
    if not suppressed then set state to "not "
    set response to (display dialog "Example alert is currently " & state & "suppressed." buttons {"Clear", "Set", "Continue"} default button 3)
    if button returned of response is "Set" then
        set my suppressed to true
    else if button returned of response is "Clear" then
        set my suppressed to false
    end if
    doAlert()
end applicationWillFinishLaunching:

on doAlert()
    log "performing doAlert() handler"
    if suppressed then return -- skip it
    tell current application's NSAlert's alloc's init()
        its setMessageText:"Alert test"
        its setInformativeText:"This is a test"
        its setAlertStyle:2
        its setShowsSuppressionButton:true
        its addButtonWithTitle:"Cancel"
        its addButtonWithTitle:"Replace"
        its showOverWithSuppress:theWindow calling:"alertDidEnd:"
    end tell
end doAlert

on alertDidEnd:response
    set buttonName to (first item of response) as text
    if buttonName = "Cancel" then display alert "Cancel button clicked!"
    set my suppressed to (second item of response) as boolean
end alertDidEnd:

on applicationShouldTerminate:sender
    tell current application's NSUserDefaults's standardUserDefaults
        its setObject:suppressed forKey:"SuppressAlert" — update
    end tell
    return current application's NSTerminateNow
end applicationShouldTerminate:

推荐阅读