Search code examples
objective-cxcodemacoscocoanssearchfield

Clickable search icon in NSSearchField and fading background


I would like to make an NSSearchField, just like the one in Ecoute 3.0. The search icon in the search field should be clickable and expand and collapse if you click it.

enter image description here enter image description here

How can you achieve this? I have searched the documentation, but didn't come up with anything useful. I could implement the expanding with the animator proxy, so that is clear.

Another thing is that the background fades in/fades out as it expands/collapses. How can I achieve this?

I would be thankful for any advices, sample code, etc.

EDIT

Ok I found the first part out myself.

- (void) resetSearchButtonCell {
    NSButtonCell *c= [[NSButtonCell alloc] init];
    [c setButtonType:NSMomentaryChangeButton];  // configure the button
    [c setBezelStyle:NSRegularSquareBezelStyle];    // configure the button
    [c setBordered:NO];
    [c setBezeled:NO];
    [c setEditable:NO];
    [c setImagePosition:NSImageOnly];
    [c setImage:[NSImage imageNamed:@"search"]];
    [c setAlternateImage:[NSImage imageNamed:@"search-pushed"]];
    [c setTarget:self];
    [c setAction:@selector(_search:)];
    [self setSearchButtonCell:c];
}

Now, I have made a property isCollapsed, which I toggle in _search:. And in the setIsCollapsed: setter method I do the following:

NSRect newRect = self.frame;

if (_isCollapsed) {
    newRect.size.width = kCollapsedWidth;
} else {
    newRect.size.width = kEXpandedWidth;
}

[[self animator] setFrameSize:newRect.size];

But for some reason the frame is being reset to the initial size, the one set in Interface Builder, when the NSSearchField gets or looses focus.

Can anyone tell me why?

EDIT

I have solved that problem too. It was auto-layout, which messed up the animation. Now, the only thing remaining is the background-alpha, which should change. I could redraw the entire thing, but is there another solution where I could just modify the alpha of only the background and the cancel-button?


Solution

  • I ended up redrawing the background. Like this I was able to set the alpha of it.

    The source code is available on Github:

    https://github.com/iluuu1994/ITSearchField