在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 = @"";
}