gpt4 book ai didi

objective-c - 像 Cocoa 中的 iTunes 一样滚动文本

转载 作者:行者123 更新时间:2023-12-03 17:22:20 25 4
gpt4 key购买 nike

我已阅读答案: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”。在 Controller 中我做:

ScrollingTextView *test = [[ScrollingTextView alloc] init];
[test setText:@"Test long text scrolling!"];
[test setSpeed:0.01];

但是当我运行它时没有任何反应,你能帮我一下吗?谢谢!

最佳答案

ScrollingTextView *test = [[ScrollingTextView alloc] init];

这样做意味着您正在创建一个新的 ScrollingTextView,而不是引用在 .xib 中创建和初始化的一个 Interface Builder

在您的 View Controller 中将ScrollingTextView设置为IBOutlet

(IBOutlet)ScrollingTextView *test;

从界面构建器中分配拖入其中的 CustomView,作为 View Controller 的引用导出。这就是初始化 ScrollingTextView 类的方式。

现在调用你的 setTest: 和 setSpeed: 它应该可以正常工作。

关于objective-c - 像 Cocoa 中的 iTunes 一样滚动文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19761596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com