iTunes 歌曲标题在 Cocoa 中滚动

2024-01-01

我进行了广泛的搜索,但我无法找到任何有关如何在 Cocoa 中文本太大的情况下实现与 iTunes 歌曲标题滚动类似的效果的信息。我尝试在 NSTextField 上设置边界但无济于事。我尝试过使用 NSTextView 以及使用 NSScrollView 的各种尝试。我确信我错过了一些简单的东西,但任何帮助将不胜感激。如果可能的话,我也希望不必使用 CoreGraphics。

Example http://cybernetnews.com/wp-content/uploads/2008/10/itunes-streaming-radio-1.png,注意“Base.FMhttp://www http://www.” 文本已滚动。如果您需要更好的示例,请打开 iTunes,其中包含一首标题相当大的歌曲,然后观看它来回滚动。

我认为肯定有一种简单的方法可以使用 NSTextField 和 NSTimer 创建选取框类型效果,但可惜。


我可以看到,如果您试图将功能硬塞到现有控件中,这将是多么困难。然而,如果你只是从一个普通的 NSView 开始,那也没有那么糟糕。我花了大约10分钟就搞定了这个...

//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;

- (void) dealloc {
    [text release];
    [scroller invalidate];
    [super dealloc];
}

- (void) setText:(NSString *)newText {
    [text release];
    text = [newText copy];
    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;

        [scroller invalidate];
        scroller == nil;
        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.

    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”即可。然后(在代码中),你可以:

[myScrollingTextView setText:@"This is the text I want to scroll"];
[myScrollingTextView setSpeed:0.01]; //redraws every 1/100th of a second

这显然是相当初级的,但它可以完成您正在寻找的内容,并且是一个不错的起点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iTunes 歌曲标题在 Cocoa 中滚动 的相关文章

随机推荐