NSTokenField 点击自动完成列表项目

3

我在我的应用程序中有一个 NSTokenField,我实现了 tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem: 方法,在这个方法中我使用 setTokenizingCharacterSet: 方法指定接收器的分词字符集:

  def tokenField(tokenField, completionsForSubstring:substring, indexOfToken:tokenIndex, indexOfSelectedItem:selectedIndex)
    tokenField.setTokenizingCharacterSet(NSCharacterSet.whitespaceAndNewlineCharacterSet)
  end

当我按下空格键或回车键时,它能够按预期工作。我也希望在使用鼠标点击完成列表中的某个项目时能够获得相同的行为。

这有可能实现吗?

谢谢你的帮助。

2个回答

3

我不知道是否可能在NSTokenField中实现这种行为。

但是你应该看一下MTTokenField,它可以直接实现你想要的功能。

为此,您需要:

1.创建一个Xcode项目作为静态库(不启用ARC)。

2.将您的项目保存到vendor / MTTokenField。

3.将位于子目录“MTTokenField”中的所有MTTokenField文件拖放到新的XCode项目中。选择复制文件。

4.将以下内容添加到rakefile中,以便将库与Rubymotion项目编译和链接。

app.vendor_project("vendor/MTTokenField/", :xcode, :xcodeproj => "MTTokenField.xcodeproj", :target => "MTTokenField", :products => ["libMTTokenField.a"], :headers_dir => "MTTokenField")

5. 在Interface Builder中将您的NSTokenField类更改为NSTextField,然后设置其自定义类为MTTokenField,并且还要更改单元格的自定义类:MTTokenFieldCell而不是NSTextFieldCell。

6. 然后,您需要将MTTokenField的代理设置为一个必须响应以下内容的类:

def tokenField(tokenField, completionsForSubstring: substring )
   # your have to return an array containing your results matching substring.
end

就是这样。它应该可以工作。

希望能有所帮助!


2

我找到了另一种使用 NSTokenField 而不是 MTTokenField 的解决方案。

在我的 NSTokenField 委托中,我使用了 NSControl 的 controlTextDidChange 方法,该方法在我在标记字段中写入字符时调用。在此方法中,我检查是否触发了 NSLeftMouseUp 事件,如果是,则模拟单击返回键。就这样。

def controlTextDidChange(aNotification)
  application = NSApplication.sharedApplication
  event = application.currentEvent
  if event.type == NSLeftMouseUp
    e1 = CGEventCreateKeyboardEvent(nil, 0x24, true)
    CGEventPost(KCGSessionEventTap, e1)
  end
end

还有一件事需要做才能使其正常工作:问题在于,如果我有一个包含3个项目的完成列表,例如,其中一个将被默认选择,比如第一个。在这种情况下,如果我点击第二个或第三个项目,则解决方案将按预期工作,但我必须双击第一个项目才能使其工作。
为了解决这个问题,请关闭自动完成并仅显示建议框,即将此行添加到tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem:方法中:
selectedIndex[0] = -1

有没有想过用Swift怎么做这个? - jpgr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接