私は答えを読んだ: iTunes Song Title Scrolling in Cocoa
そして、ここに私が書いたコードがあります:
// ScrollingTextView.h
#import <Cocoa/Cocoa.h>
@interface ScrollingTextView : NSView {
NSTimer *scroller;
NSPoint point;
NSString *text;
NSTimeInterval speed;
CGFloat stringWidth;
}
@property (nonatomic, copy) NSString *text;
@property (nonatomic) NSTimeInterval speed;
@end
// ScrollingTextView.m
#import "ScrollingTextView.h"
@implementation ScrollingTextView
@synthesize text;
@synthesize speed;
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)dealloc {
[scroller invalidate];
}
- (void)setText:(NSString *)newText {
text = [newText copy];
NSLog(@"t: %@", text);
point = NSZeroPoint;
stringWidth = [newText sizeWithAttributes:nil].width;
if (scroller == nil && speed > 0 && text != nil) {
scroller = [NSTimer scheduledTimerWithTimeInterval:speed target:self selector:@selector(moveText:) userInfo:nil repeats:YES];
}
}
- (void)setSpeed:(NSTimeInterval)newSpeed {
if (newSpeed != speed) {
speed = newSpeed;
NSLog(@"s: %f", speed);
[scroller invalidate];
if (speed > 0 && text != nil) {
scroller = [NSTimer scheduledTimerWithTimeInterval:speed target:self selector:@selector(moveText:) userInfo:nil repeats:YES];
}
}
}
- (void)moveText:(NSTimer *)timer {
point.x = point.x - 1.0f;
[self setNeedsDisplay:YES];
}
- (void)drawRect:(NSRect)dirtyRect {
// Drawing code here.
[super drawRect:dirtyRect];
if (point.x + stringWidth < 0) {
point.x += dirtyRect.size.width;
}
[text drawAtPoint:point withAttributes:nil];
if (point.x < 0) {
NSPoint otherPoint = point;
otherPoint.x += dirtyRect.size.width;
[text drawAtPoint:otherPoint withAttributes:nil];
}
}
@end
次に、NSView を Interface Builder のメイン ウィンドウにドラッグし、そのクラスを「ScrollingTextView」に変更します。コントローラーで私は:
ScrollingTextView *test = [[ScrollingTextView alloc] init];
[test setText:@"Test long text scrolling!"];
[test setSpeed:0.01];
しかし、実行しても何も起こりませんでした。手を貸していただけますか? ありがとうございました!