我是 Swift 新手,来自 AppleScript Obj-C。我已经阅读了几本书并且对语法感到满意,但我仍然感到很失落。
我正在尝试创建一个简单的令牌字段,当它识别您的联系人中的电子邮件时,它会建议像 Apple Mail 那样的自动完成令牌。我的灵感来自这个 ASOC 脚本(帖子 #6)。我试图尽可能快速地复制它(没有标记上的操作菜单):
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var tokenField: NSTokenField!
var theNames = [String]()
func applicationDidFinishLaunching(aNotification: NSNotification) {
tokenField.setDelegate(tokenField.delegate())
theNames = ["Pomona", "Potomac", "Potable", "Process", "Plow"]
}
func tokenField(tokenField : NSTokenField, completionsForSubstring substring : String, indexOfSelectedItem selectedIndex : UnsafeMutablePointer<Int>) -> [AnyObject]? {
var thePredicate = NSPredicate(format: "SELF beginswith[cd] %@", substring)
var matchingNames = (theNames as NSArray).filteredArrayUsingPredicate(thePredicate)
return matchingNames as Array
}
func tokenField(tokenField : NSTokenField, hasMenuForRepresentedObject representedObject : AnyObject) -> Bool {
return true
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
所以总结一下。当用户键入时,如果第一个字母是“p”,则应在单词下方弹出一个菜单,其中包含“Pomona”、“Potomac”、“Potable”、“Process”、“Plow”。我不确定为什么什么都没有弹出。
有任何想法吗?
编辑:
2016 年 2 月 13 日
ioquatix 下面提供了我的问题的答案,但这超出了我目前的知识水平。他确实指出了我原始代码中的一个关键缺陷是缺少NSTokenFieldCellDelegate
and NSTokenFieldDelegate
。感谢他的帮助,我的(简单但有限的)解决方案是:
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTokenFieldCellDelegate, NSTokenFieldDelegate {
var names = ["Pat", "Pot"]
@IBOutlet weak var tokenField: NSTokenField!
func tokenField(tokenField: NSTokenField, completionsForSubstring substring: String, indexOfToken tokenIndex: Int, indexOfSelectedItem selectedIndex: UnsafeMutablePointer<Int>) -> [AnyObject]? {
return (names as NSArray).filteredArrayUsingPredicate(NSPredicate(format: "SELF beginswith[cd] %@", substring))
}
}