3

从 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 方法?..

4

1 回答 1

2

第 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
    }


}
于 2016-05-27T18:19:19.703 回答