NSTokenField单击完成列表项

时间:2013-06-21 08:32:23

标签: objective-c macos cocoa rubymotion

我的应用程序中有一个NSTokenField我实现了tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem:方法,我用setTokenizingCharacterSet:方法指定了接收者的标记字符集:

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

当我点击空格键或输入按钮时,它按预期工作。当我用鼠标点击完成列表中的一个项目时,我也希望有相同的行为。

这怎么可能?

感谢您的帮助。

2 个答案:

答案 0 :(得分: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

就是这样。它应该工作。

希望它有所帮助!

答案 1 :(得分: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:method:

selectedIndex[0] = -1
相关问题