【问题标题】:How to get the return value of a clicked button using NSAlert如何使用 NSAlert 获取单击按钮的返回值
【发布时间】:2019-08-06 10:37:11
【问题描述】:

我正在使用以下内容:

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

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

【问题讨论】:

  • 这是针对 Xcode 项目的吗?在我的 Sierra 和 Mojave 系统上,使用didEndSelector 会在使用除默认按钮以外的任何其他内容时使应用程序崩溃,因此看起来早期的错误又回来了 - 虽然通过 Myriad Helpers 类别使用基于块的方法工作正常。
  • 是的,它是针对一个xcode项目的,有什么办法吗?

标签: applescript-objc


【解决方案1】:

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

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:

【讨论】:

  • 是的,如果您对抑制结果使用属性或全局变量,那么以后可以使用它来确定是否再次显示警报。
  • 如果我想选择类似 if 和 else 我应该像这样包含它们:if buttonCancel = "Cancel" then display alert"Button Cancel clicked!" end if
  • 你能给我举个例子吗?我想记住用户使用抑制按钮的决定
  • 通常这种事情会通过偏好设置或其他方式来保存到用户默认值来重置它,所以我将它添加到我的示例中。请注意,如果您使用 Xcode 停止应用程序,则不会更新用户默认值。
猜你喜欢
  • 2013-05-13
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
相关资源
最近更新 更多