Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating label (NSTextField) horizontally

I have a NSTextField as a label, showing a string. I want to animate this label from right to left, if the content of it is too large to be displayed at once.

I've done this with an NSTimer so far, it works, but it's just not a very good solution. The labels are displayed in an NSTextFieldCell, in a Table View. They often get out of sync, and I guess it's just eating up a lot of CPU/GPU resources.

Is there another way with Core Animation to do this?

I have tried it with layers, as you can see right here: CALayer and drawRect

but I didn't get it working either.

I would really appreciate your help.

like image 853
IluTov Avatar asked Oct 22 '25 19:10

IluTov


1 Answers

You can simply animate the position of NSTextField with animator like

[[textField animator] setFrameOrigin:NSMakePoint(x,y)];

you can also embed it in "CATrancation" code like this:

[CATransaction begin];
[CATransaction setAnimationDuration:0.5];
[CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
[[textField animator] setFrameOrigin:NSMakePoint(x,y)];
[CATransaction commit];

if you need animation delegate, you can use CABasicAnimation

CABasicAnimation* animation = [CABasicAnimation animation];
animation.delegate = self;
NSDictionary *animations = [NSDictionary dictionaryWithObjectsAndKeys:animation,@"frameOrigin",nil]; 
[textField setAnimations:animations];
[[textField animator] setFrameOrigin:NSMakePoint(x,y)];

Delegate methods are

- (void)animationDidStart:(CAAnimation *)theAnimation;
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag;

If you need to mask your text field, just embed it in other NSView.

like image 196
Remizorrr Avatar answered Oct 24 '25 13:10

Remizorrr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!