在NSTokenField上点击鼠标

Fre*_*man 6 cocoa nstokenfield nstextattachment swift

我想实现一个NSTokenField,它将显示令牌 - 当鼠标悬停在令牌上时 - 显示一个删除图标.随后当我点击图标时,我希望删除令牌.

经过大量搜索后,似乎标准NSTokenField无法实现这一点.如果有人知道如何请让我知道.

我查看了https://github.com/octiplex/OEXTokenField,并根据该代码在Swift中创建了一个CustomTokenField实现.到目前为止,我有一个工作的CustomTokenField,当我将鼠标悬停在令牌上时,它会显示一个删除图标.

下一阶段结果是一个我无法弄明白的问题.如何点击令牌触发回调.?

令牌类派生自NSTextAttachmentCell,CustomTokenField派生自NStokenField:

class CustomTokenAttachmentCell: NSTextAttachmentCell {
    . . .
}

class CustomTokenField: NSTokenField {
    . . .
}
Run Code Online (Sandbox Code Playgroud)

我试图用两个不同的角度来解决这个问题:

通过CustomTokenAttachmentCell

NSTextAttachmentCell实现NSTextAttachmentCellProtocol.

public protocol NSTextAttachmentCellProtocol : NSObjectProtocol {
    . . .
    public func wantsToTrackMouse() -> Bool
    public func highlight(flag: Bool, withFrame cellFrame: NSRect, inView controlView: NSView?)
    public func trackMouse(theEvent: NSEvent, inRect cellFrame: NSRect, ofView controlView: NSView?, untilMouseUp flag: Bool) -> Bool
    . . .
}
Run Code Online (Sandbox Code Playgroud)

这是有希望的.所以我在CustomTokenAttachmentCell中实现了这些方法,并且实际上正在调用wantsToTrackMouse().我已经实现了返回'true'.

override func trackMouse(theEvent: NSEvent, inRect cellFrame: NSRect, ofView controlView: NSView?, untilMouseUp flag: Bool) -> Bool {
    Swift.print(“trackMouse”)
    return true
}

override func highlight(flag: Bool, withFrame cellFrame: NSRect, inView controlView: NSView?) {
    Swift.print("highlight")
}

override func wantsToTrackMouse() -> Bool {
    Swift.print(“trackMouse”)
    return true
}
Run Code Online (Sandbox Code Playgroud)

永远不会调用另外两种方法.还有什么需要做才能让他们被召唤吗?

通过CustomTokenField

我也尝试从CustomTokenField中解决这个问题.可以使用MouseDown()获取鼠标事件,但是我找不到从单元格实际访问令牌的方法.

我在StackOverflow上看过很多帖子,我看过提示但是没有一个看起来指向正确的方向.

不知怎的,我得出的结论是,在层次结构中存在NSControl的情况下,您只能获取鼠标事件.对于令牌并非如此.NSControl是视图层次结构的一部分,因此我试图通过CustomTokenField实现这一点,但我也在那里运行.例如,此问题在NSTokenField中单击令牌完全相同,但设置操作或目标将生成致命错误,因为setActionsetTarget是基类的存根.

我是Coacoa的初级程序员,所以希望这只是缺乏知识的问题.

任何建议将不胜感激.

Gli*_*gor 0

您是否尝试过在整个CustomTokenAttachmentCell视图之上添加 NSButton ?然后添加一个@IBOutlet action用于单击的按钮,并通过委托将其传递到TokenField您可以控制显示的令牌的位置。

我也尝试在我的应用程序中实现这一点,因此,如果您能够分享任何代码,我们将不胜感激。谢谢!