我使用swift 4 for osx,我想实现像apple maps这样的地址自动完成功能:
我该怎么做图像显示? 我猜结构将是:
更新 现在我的应用程序是这样的:
太棒了。 但是有一个小问题:
我将第一个字符写入文本字段,弹出窗口将显示,文本字段失去焦点。现在我必须再次点击我的文本字段继续。有没有办法保持这个文本域的重点?
答案 0 :(得分:1)
我将Apple的“CustomMenus”示例从Objective-C移植到Swift。该示例包括NSSearchField的搜索完成下拉菜单:
https://github.com/dougzilla32/CustomMenus
Objective-C中Apple网站上的原始示例:
https://developer.apple.com/library/content/samplecode/CustomMenus
答案 1 :(得分:0)
我解决了这样的情况:
使用override func controlTextDidChange(_ obj: Notification) {
vcAddress.searchString = txtSourceAddress.stringValue
self.presentViewController(vcAddress, asPopoverRelativeTo: txtSourceAddress.bounds, of: txtSourceAddress, preferredEdge: .maxX, behavior: .semitransient)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "AutoComplete"), object: nil)
}
并提供一个popover
import Cocoa
import MapKit
class AcAddress: NSViewController, NSTableViewDelegate, NSTableViewDataSource, MKLocalSearchCompleterDelegate {
var searchString:String?
var searchCompleter = MKLocalSearchCompleter()
var searchResults = [MKLocalSearchCompletion]()
@IBOutlet weak var tblAutoComplete: NSTableView!
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(AutoComplete), name: NSNotification.Name(rawValue: "AutoComplete"), object: nil)
searchCompleter.delegate = self
tblAutoComplete.refusesFirstResponder = true
}
@objc func notificationAutoComplete() {
searchCompleter.queryFragment = searchString ?? ""
}
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
searchResults = completer.results
tblAutoComplete.reloadData()
}
func numberOfRows(in tableView: NSTableView) -> Int {
return searchResults.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
// FILL IT
}
}
popover有一个tableview,可以使用SearchCompleter(MapKit)获取建议
SELECT custlastname || ', ' || custfirstname as custname, postalcode, city, state, phone
FROM (SELECT c.*,
MAX(num_customers) OVER () as max_num_customers
FROM (SELECT c.*,
COUNT(*) OVER (PARTITION BY postalcode) as num_customers
FROM customer c
) c
) c
WHERE max_num_customers = num_customers;