Cocoa focus ring color animation

2019-07-10 06:44发布

I want to use a focus ring animation as an indicator of incorrect data in field. So I'm sending becomeFirstResponder: to field and want focus ring to fade from red to default color.

I'm wrestling with Core Animation but still have not found any way to do it. Is it possible?

1条回答
forever°为你锁心
2楼-- · 2019-07-10 07:22

I'm not sure if this strategy follows the HIG, its often more common to do something like display a persistent icon indicating a field doesn't validate next to the field, but it shouldn't be too hard to get the effect you're seeking.

It might be easier to use a simple NSAnimation here instead of using Core Animation. The standard code for drawing a focus ring generally goes something like the following:

[NSGraphicsContext saveGraphicsState];
NSSetFocusRingStyle(NSFocusRingOnly);
[[NSColor clearColor] set];
[[NSBezierPath bezierPathWithRect:focusRect] fill];
[NSGraphicsContext restoreGraphicsState];

This code would be implemented in the drawRect: method in custom subclass of your control.

In order to draw a custom colored focus ring, you'll need to draw the rectangle yourself, and won't be able to benefit from the NSSetFocusRingStyle function. The color would be driven off of the NSAnimation, which would also set the control to repaint itself. Because you're not using Cocoa's facilities to draw the focus ring, you'll also probably need to inset the content of your view so you'll have space to draw the ring.

More information regarding NSAnimations is available in the Animation Programming Guide for Cocoa

查看更多
登录 后发表回答