簡體   English   中英

NSTextField 和 NSTouchbar

[英]NSTextField and NSTouchbar

我正在實現觸摸欄功能。 我希望在編輯NSTextField時顯示特定的觸摸欄。

我試過這兩種方法:

  • 使用touchbar屬性設置觸摸touchbar
field.touchBar = myTouchBar
  • makeTouchBar() NSTextField以覆蓋makeTouchBar()函數:
class MyTextField: NSTextField
{
   override func makeTouchBar(){return myTouchBar}
}

兩種方法在編輯字段時都顯示一個空的觸摸欄。 更改isAutomaticTextCompletionEnabledallowsCharacterPickerTouchBarItem屬性不會改變它 - 只是讓相應的按鈕出現。

然而,使用NSTextView或許多其他類型的NSView做完全相同的事情,效果非常好。

您知道在編輯NSTextField時是否可以有自定義工具欄嗎?

感謝@Willeke 的回答,我已經能夠找到解決方案。 然而,這是相當棘手的:

  • 首先, NSTouchBar NSTextField以保留另一個NSTouchBar
class MyTextField: NSTextField
{
    private var innerTouchBar: Any?
    var editor: NSText?

    @available(OSX 10.12.2, *)
    func setTouchBar(_ touchBar: NSTouchBar?)
    {
        innerTouchBar = touchBar
    }

    @available(OSX 10.12.2, *)
    func getTouchBar() -> NSTouchBar?
    {
        innerTouchBar as? NSTouchBar
    }
}
  • 然后, NSTextView以使用提供的NSTouchBar
@available(OSX 10.12.2, *)
class MyTextView: NSTextView
{
    private var innerTouchBar: NSTouchBar?

    convenience init(touchBar: NSTouchBar?)
    {
        self.init()
        innerTouchBar = touchBar
    }

    override func makeTouchBar() -> NSTouchBar?
    {
        innerTouchBar
    }
}
  • NSWindowController被要求將NSTextView的的NSTextField ,然后創建一個自定義NSTextViewinnerTouchBar的的NSTextField
extension MyWindowController
{
    func windowWillReturnFieldEditor(_ sender: NSWindow, to client: Any?) -> Any?
    {
        if #available(OSX 10.12.2, *)
        {
             if let field = client as? MyTextField
            {
                if field.editor == nil
                {
                    field.editor = SFTextView(touchBar: field.getTouchBar())
                    field.editor?.isFieldEditor = true
                }
                return field.editor
            }
        }
        return nil;
    }
}
  • 當然,不要忘記在 XIB 或您的代碼中使用MyTextField而不是NSTextField ,並在創建后首先調用setTouchBar(_:)函數。

解釋

每個NSTextField都有一個底層NSTextView ,它實際上是 firstResponder,以及顯示其 touchBar 的對象。 我們不能直接從NSTextField訪問底層NSTextView 相反, NSTextField詢問NWindowControllerNSTextView使用。 所以,當出現這種情況,在windowWillReturnFieldEditor(_:,to:)NSWindowController ,我們必須返回一個自定義NSTextView用正確的觸摸欄。 我認為這可以適用於 touchBar 以外的其他東西......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM