【问题标题】:Looking for example of how to display text in an NSWindow programmatically?寻找如何以编程方式在 NSWindow 中显示文本的示例?
【发布时间】:2019-05-27 20:21:49
【问题描述】:

我正在尝试在 HUD 样式的半透明窗口中显示文本。我已经设置了窗口的代码,但是我已经搜索了两天的文档,还没有想出一种可以在窗口中实际显示文本的方法。由于我在脚本调试器中使用 AppleScriptObjC,而不是 Xcode,我宁愿以编程方式执行此操作,而不必切换到 Xcode 并使用 IB。 (我确实花了一些时间在玩 IB,但说实话并不是很直观。所以我想在阅读如何开始使用 IB 的指南之前先检查一下这个表格)。

所以我得到了一些建议,“创建一个 NSTextField 并将其添加到窗口的 contentView”。因此,我尝试了许多不同的设置来尝试初始化 NSTextField(和 NSTextView),并且我可能已经能够正确处理该部分,但是让文本实际显示在窗口中比我预期的要大。我已经包含了我用来生成窗口的代码的代码片段。

tell (NSWindow's alloc()'s ¬
            initWithContentRect:{{theWidth, theHeight}, {640, 480}} ¬
                styleMask:NSBorderlessWindowMask ¬
                backing:NSBackingStoreBuffered ¬
                defer:true)

            setOpaque_(yes)
            setAlphaValue_(0.5)
            setBackgroundColor_(NSColor's grayColor())
            setReleasedWhenClosed_(yes)
            setExcludedFromWindowsMenu_(yes)
            orderFrontRegardless()
            delay 1
            |close|()
        end tell

我希望能够在该窗口中获得一个 NSText 视图,以便在其中显示一些文本。到目前为止,我还没有接近。我通常得到的错误是关于“发送到实例的无法识别的选择器”。所以很明显我做错了什么。我希望有一种我还没有遇到过的简单方法来实现这一点。

【问题讨论】:

  • 当我在脚本编辑器或脚本调试器中运行完整的脚本(我只发布了一个 sn-p)时,我会显示 NSWindow。您可以从脚本编辑器或脚本调试器中调用 AppKit 框架。如果您想尝试一下,我可以发布完整的脚本。

标签: nswindow nstextfield nstextview applescript-objc


【解决方案1】:

听起来有些方法没有目标。在tell 语句中,通常隐含目标,但有时AppleScript 无法识别。你也没有得到更新的方法语法,所以我有更好的运气只为所有东西指定目标 - 另请注意,通常可以直接设置对象属性,而不是使用它们的 setter 方法。

从你的sn-p我看不出来,但是你还需要将textView添加到窗口的contentView中,例如:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

# create a text view
tell (current application's NSTextView's alloc's initWithFrame:{{20, 20}, {600, 440}})
  set theTextView to it
end tell

# create a window
tell (current application's NSWindow's alloc()'s ¬
    initWithContentRect:{{200, 600}, {640, 480}} ¬
    styleMask:(current application's NSBorderlessWindowMask) ¬
    backing:(current application's NSBackingStoreBuffered) ¬
    defer:true)
  set theWindow to it
  set its opaque to true
  set its alphaValue to 0.5
  set its backgroundColor to (current application's NSColor's grayColor)
  set its releasedWhenClosed to true
  set its excludedFromWindowsMenu to true
end tell

theWindow's contentView's addSubview:theTextView
theTextView's setString:"this is a test"
theWindow's orderFrontRegardless()
delay 5
theWindow's |close|()

【讨论】:

  • 我知道已经过去了几个星期,但我已经为此做了一些工作,还有一些其他问题。我应该发布一个新问题还是直接在这里提问?
  • 除非您只需要澄清或与此特定问题相关的内容,否则您可能应该问一个新问题。
猜你喜欢
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 2018-07-27
  • 2013-05-14
  • 1970-01-01
相关资源
最近更新 更多