Created
March 23, 2016 19:44
-
-
Save codelynx/aa7a41f5fd8069a3cfa2 to your computer and use it in GitHub Desktop.
ZSearchField is able to detect when focused or unfocused to its delegate. If you are using Interface Builder make sure to change the NSSerachField class to ZSearchField, and t's delegate must conforms to ZSearchFieldDelegate not NSTextFieldDelegate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol ZSearchFieldDelegate: NSTextFieldDelegate { | |
func searchFieldDidBecomeFirstResponder(textField: ZSearchField) | |
func searchFieldDidResignFirstResponder(textField: ZSearchField) | |
} | |
class ZSearchField: NSSearchField, NSTextDelegate { | |
var expectingCurrentEditor: Bool = false | |
// When you clicked on serach field, it will get becomeFirstResponder(), | |
// and preparing NSText and focus will be taken by the NSText. | |
// Problem is that self.currentEditor() hasn't been ready yet here. | |
// So we have to wait resignFirstResponder() to get call and make sure | |
// self.currentEditor() is ready. | |
override func becomeFirstResponder() -> Bool { | |
let status = super.becomeFirstResponder() | |
if let _ = self.delegate as? ZSearchFieldDelegate where status == true { | |
expectingCurrentEditor = true | |
} | |
return status | |
} | |
// It is pretty strange to detect search field get focused in resignFirstResponder() | |
// method. But otherwise, it is hard to tell if self.currentEditor() is available. | |
// Once self.currentEditor() is there, that means the focus is moved from | |
// serach feild to NSText. So, tell it's delegate that the search field got focused. | |
override func resignFirstResponder() -> Bool { | |
let status = super.resignFirstResponder() | |
if let delegate = self.delegate as? ZSearchFieldDelegate where status == true { | |
if let _ = self.currentEditor() where expectingCurrentEditor { | |
delegate.searchFieldDidBecomeFirstResponder(self) | |
// currentEditor.delegate = self | |
} | |
} | |
self.expectingCurrentEditor = false | |
return status | |
} | |
// This method detect whether NSText lost it's focus or not. Make sure | |
// self.currentEditor() is nil, then that means the search field lost its focus, | |
// and tell it's delegate that the search field lost its focus. | |
override func textDidEndEditing(notification: NSNotification) { | |
super.textDidEndEditing(notification) | |
if let delegate = self.delegate as? ZSearchFieldDelegate { | |
if self.currentEditor() == nil { | |
delegate.searchFieldDidResignFirstResponder(self) | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment