簡體   English   中英

通過雙擊防止編輯 NSTextField

[英]Prevent editing of NSTextField by double right-click

我正在使用 MonoMac/C# 並有一個 NSOutlineView,其中一些項目是可編輯的。 因此,如果您選擇一個項目,然后再次單擊它(緩慢雙擊),該行的 NSTextField 將進入編輯模式。 我的問題是,即使您右鍵單擊該項目,也會發生這種情況。 您甚至可以混合左鍵單擊和右鍵單擊以進入編輯模式。

這很煩人,因為您有時會選擇一行然后右鍵單擊它,然后在上下文菜單出現后一秒鍾,該行進入編輯模式。

有沒有辦法限制 NSOutlineView 或其中的 NSTextFields,只使用鼠標左鍵進入編輯模式(除了在選擇行時按 Enter 鍵)?

謝謝!

我使用的方法是覆蓋“RightMouseDown”方法 [1, 2]。 在嘗試在 NSOutlineView 和 NSTableCellView 中這樣做但沒有運氣之后,訣竅是向下到層次結構中的較低級別到 NSTextField。 事實證明,NSWindow 對象使用 SendEvent 將事件直接分派到最接近鼠標事件的視圖 [3],因此事件從最里面的視圖到最外面的視圖進行。

您可以在 Xcode 的 OutlineView 中更改所需的 NSTextField 以使用此自定義類:

public partial class CustomTextField : NSTextField
{
    #region Constructors

    // Called when created from unmanaged code
    public CustomTextField (IntPtr handle) : base (handle)
    {
        Initialize ();
    }
    // Called when created directly from a XIB file
    [Export ("initWithCoder:")]
    public CustomTextField (NSCoder coder) : base (coder)
    {
        Initialize ();
    }
    // Shared initialization code
    void Initialize ()
    {
    }

    #endregion

    public override void RightMouseDown (NSEvent theEvent)
    {
        NextResponder.RightMouseDown (theEvent);
    }
}

因為“RightMouseDown”base.RightMouseDown()點擊完全由邏輯的NSTextField忽略。 調用 NextResponder.RightMouseDown() 允許事件在視圖層次結構中向上滲透,以便它仍然可以觸發上下文菜單。

[1] https://developer.apple.com/library/mac/documentation/cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html#//apple_ref/occ/instm/NSView/rightMouseDown : [2] https://developer.apple.com/library/mac/documentation/cocoa/conceptual/eventoverview/HandlingMouseEvents/HandlingMouseEvents.html [3] https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ eventoverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW21

@salgarcia 上面的回答可以適用於原生 Swift 3 代碼,如下所示:

import AppKit

class CustomTextField: NSTextField {

    override func rightMouseDown(with event: NSEvent) {

        // Right-clicking when the outline view row is already
        // selected won't cause the text field to go into edit 
        // mode. Still can be edited by pressing Return while the
        // row is selected, as long as the textfield it is set to 
        // 'Editable' (in the storyboard or programmatically):

        nextResponder?.rightMouseDown(with: event)
    }
}

暫無
暫無

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

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