Cocoa - 未调用NSSearchFieldDelegate方法

时间:2016-03-24 13:07:40

标签: cocoa nssearchfield nscontrol

我在NSVIewConroller视图上有简单的NSSearchField。并将NSSearchFIeld的委托连接到视图控制器。我已经实现了NSSearcHFieldDelegate方法,如下所示:

- (void)searchFieldDidStartSearching:(NSSearchField *)sender NS_AVAILABLE_MAC(10_11);
{
    NSLog(@"search field did start: %@", sender.stringValue);
}
- (void)searchFieldDidEndSearching:(NSSearchField *)sender NS_AVAILABLE_MAC(10_11);
{
    NSLog(@"search field did end: %@", sender.stringValue);

}

在开始编辑和结束编辑时不会调用这些方法。但是,如果我实现NSControl,则会在相应的事件上调用controlTextDidChange:control:textShouldBeginEditing:等默认委托。

为什么不调用NSSearchFieldDelegate方法?..

1 个答案:

答案 0 :(得分:3)

Step 1: Your controller class needs to inherit from NSSearchFieldDelegate
Step 2: Implement the below 2 methods
    func searchFieldDidStartSearching(sender: NSSearchField){
        print("searchFieldDidStartSearching \(sender.stringValue)")
    }
    func searchFieldDidEndSearching(sender: NSSearchField){
        print("searchFieldDidEndSearching \(sender.stringValue)")
    }
Step 3: in the viewDidLoad, windowDidLoad, awakeFromNib etc set the delegate for the search field as the view controller/ window controller etc
 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
    }


}