第 1 步:您的控制器类需要从 NSSearchFieldDelegate 继承
第 2 步:实现以下 2 种方法
func searchFieldDidStartSearching(sender: NSSearchField){
print("searchFieldDidStartSearching \(sender.stringValue)")
}
func searchFieldDidEndSearching(sender: NSSearchField){
print("searchFieldDidEndSearching \(sender.stringValue)")
}
第 3 步:在 viewDidLoad、windowDidLoad、awakeFromNib 等中将搜索字段的委托设置为视图控制器/窗口控制器等
self.searchField.delegate = self
工作样本如下
// AppDelegate.swift
// NSSearchFieldDelegateSampleCode
// Created by Debasis Das on 27/05/16.
// Copyright © 2016 Knowstack. All rights reserved.
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSSearchFieldDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var searchField:NSSearchField!
func searchFieldDidStartSearching(sender: NSSearchField){
print("searchFieldDidStartSearching \(sender.stringValue)")
}
func searchFieldDidEndSearching(sender: NSSearchField){
print("searchFieldDidEndSearching \(sender.stringValue)")
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
self.searchField.delegate = self
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}