Skip to content

Instantly share code, notes, and snippets.

@Kapeli
Last active March 9, 2020 18:57
Show Gist options
  • Save Kapeli/7abd83d966957c17a827 to your computer and use it in GitHub Desktop.
Save Kapeli/7abd83d966957c17a827 to your computer and use it in GitHub Desktop.
Yosemite NSSearchField Fixes
// 1. Disable centered look & animation:
// 1.1. Subclass NSSearchFieldCell and add:
- (BOOL)isCenteredLook
{
return NO;
}
// 1.2. Subclass NSSearchField and add:
- (void)setWantsLayer:(BOOL)wantsLayer
{
}
- (BOOL)wantsLayer
{
return NO;
}
- (CALayer *)makeBackingLayer
{
return nil;
}
// 2. To fix cursor not blinking when the search field becomes first responder,
// subclass NSSearchField and add:
- (BOOL)becomeFirstResponder
{
BOOL result = [super becomeFirstResponder];
if(result)
{
[self ensureCursorBlink];
}
return result;
}
- (void)selectText:(id)sender
{
[self ensureCursorBlink];
[super selectText:sender];
}
- (void)ensureCursorBlink
{
if(isYosemite && !self.stringValue.length)
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if(!self.stringValue.length)
{
[self setStringValue:@" "];
[self setStringValue:@""];
}
});
}
}
// 3. If you're having issues updating the placeholder or image, this seems to cause the
// search field to update properly. This used to be needed in the GM, but no longer is
// the case in the final release (at least not with the not-centered look). YMMV:
[searchField setHidden:YES];
[searchField setHidden:NO];
// There might be other ways to do this. Note: this will also make the search field lose
// first responder, so make sure to restore it if needed.
// 4. I have a feeling I'm forgetting something, let me know if you encounter any issues.
@sfsam
Copy link

sfsam commented Aug 9, 2017

The above didn't work for me on 10.12. I'm using this which is a lot shorter and seems to work even though I don't understand why it works. Subclass NSSearchField:

- (NSRect)rectForSearchTextWhenCentered:(BOOL)isCentered {
    return [super rectForSearchTextWhenCentered:YES]; 
}

@TroikaTronix
Copy link

TroikaTronix commented Apr 14, 2018

The ensureCursorBlink method didn't solve the problem for me as it was written here.

But if you replace the two setStringValue calls with

[self mouseDown: nil];

it works like a charm for me.

P.S. The class name gave me a chuckle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment