6

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

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

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

下一个阶段结果是一个我自己无法弄清楚的问题。我怎样才能点击令牌触发回调。?

token 类派生自 NSTextAttachmentCell,CustomTokenField 派生自 NStokenField:

class CustomTokenAttachmentCell: NSTextAttachmentCell {
    . . .
}

class CustomTokenField: NSTokenField {
    . . .
}

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

通过 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
    . . .
}

这是有希望的。所以我在CustomTokenAttachmentCell中实现了这些方法,并且实际调用了wantToTrackMouse()。我已经实现了返回“真”。

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
}

其他两种方法永远不会被调用。是否需要做其他事情才能使他们被调用?

通过 CustomTokenField

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

我在 StackOverflow 上看到了很多帖子,也看到了提示,但似乎没有一个指向正确的方向。

不知何故,我得出的结论是,您只能在层次结构中有 NSControl 的情况下获取鼠标事件。对于不是这种情况的令牌。NSControl 是视图层次结构的一部分,因此我尝试通过CustomTokenField来实现这一点,但我也在那里陷入了死胡同。例如这个问题Clicking token in NSTokenField是完全相同的,但是设置动作或目标会产生致命错误,因为setActionsetTarget是基类的存根。

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

任何建议将不胜感激。

4

1 回答 1

0

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

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

于 2017-04-23T21:40:43.693 回答