NSSearchField的事件监听

https://blog.csdn.net/sinat_31177681/article/details/79714625

2018年03月27日 16:06:45 

创建一个NSSearchField的子类,继承NSSearchField,在.m文件中重写三个方法,可以监听NSSearchField的首次点击、搜索文本框变化、搜索框点击了clear button事件的监听。如下,

#import "QXSearchField.h"

 

@implementation QXSearchField

 

/**

 *  用户点击了搜索框

 */

- (void)mouseDown:(NSEvent *)event

{

    [super mouseDown:event];

    

    [_qx_SearchFieldDelegate qx_SearchFieldMouseDown:event];

}

 

/**

 *  搜索框文本变化

 */

- (void)textDidChange:(NSNotification *)notification

{

    [super textDidChange:notification];

    

    [_qx_SearchFieldDelegate qx_textDidChange:notification];

}

 

/**

 *  搜索框点击clear button

 */

- (void)textDidEndEditing:(NSNotification *)notification

{

    [super textDidEndEditing:notification];

    

    [_qx_SearchFieldDelegate qx_textDidEndEditing:notification];

}

 

@end

原文:https://blog.csdn.net/sinat_31177681/article/details/79714625

 

在iOS中使用搜索功能可能会用到NSSearchController,但是在mac OS中没有这样控制器,只能只用NSSearchField。
下面直接上代码解释怎么使用
首先拖在控件库中拖一个NSSearchField空间放到xib中。

@property (weak) IBOutlet NSSearchField *mySearchField;

这里有一个问题就是NSSearchField中最左面有一个搜索按钮,当你输入文字的时候NSSearchField中会自动生成一个清除按钮。有时候这两个按钮点击不是很灵活,这个时候需要获取到这两个按钮。分别处理。

NSActionCell *searchCell = [[self.mySearchField cell] searchButtonCell];

NSActionCell *cancelCell = [[self.mySearchField cell] cancelButtonCell];

searchCell.target = self;
searchCell.action = @selector(searchButtonClicked:);

cancelCell.target = self;
cancelCell.action = @selector(cancellButtonClicked:);

#pragma mark -- 点击搜索按钮
- (void)searchButtonClicked:(id)sender {
NSLog(@"search\n");
NSSearchField *search = sender;
NSLog(@"%@", search.stringValue);
}

#pragma mark -- 点击取消按钮
- (void)cancellButtonClicked:(id)sender {
NSLog(@"cancell");
self.mySearchField.stringValue = @"";
}
---------------------

原文:https://blog.csdn.net/tongwei117/article/details/78258456

fileprivate let searchField: NSSearchField = {

        let searchField = NSSearchField(frame: NSMakeRect(70, 30, 200, 30))

        return searchField

    }();

func registerSEarchButtonAction(){

        let searchButtonCell = self.searchField.cell as! NSSearchFieldCell

        let searchButtonActionCell = searchButtonCell.searchButtonCell!

        searchButtonActionCell.target = self

        searchButtonActionCell.action = #selector(searchButtonAction(_:))

        let cancelButtonCell = self.searchField.cell as! NSSearchFieldCell

        let cancelButtonActionCell = cancelButtonCell.cancelButtonCell!

        cancelButtonActionCell.target = self

        cancelButtonActionCell.action = #selector(cancelButtonAction(_:))

    }

    

    @objc func searchButtonAction(_ sender:NSSearchField){

        

    }

    @objc func cancelButtonAction(_ sender:NSSearchField){

        sender.stringValue = ""

    }

 

posted @ 2019-01-29 11:02  sundaysmac  阅读(764)  评论(0编辑  收藏  举报