我似乎无法将计时器输出设置为NSTextField。我在许多人中看过这个Q/A,,但必须做一些与众不同的事情。
我在WindowDidLoad中初始化计时器和文本字段。
我的计时器方法如下:
time += 1;
if((time % 60) <= 9) {
NSString *tempString = [NSString stringWithFormat:@"%d:0%d",(time/60),(time%60)];
[timerTextField setStringValue:tempString];
} else {
NSString *tempString = [NSString stringWithFormat:@"%d:%d",(time/60),(time%60)];
timerTextField.stringValue = tempString;
}
NSLog(@"timerTextField: %@", timerTextField.stringValue);
如您所见,我记录了文本字段输出。 我有一个从File的所有者到timerTextField的IBOutlet连接。
我可以在日志中正确看到输出,但是没有填充文本字符串。
任何人都能看到我做错的事吗?感谢
答案 0 :(得分:1)
您发布的代码对我来说很合适。 (您可以通过Cocoa Bindings将timerTextField
绑定到时间值来替换它。)
你是如何创建计时器的,以及你添加了哪个runloop(模式)?
另一个问题可能是timerTextField
的插座没有连接。您可以在计时器选择器中设置断点,并检查timerTextField
是否为零。
<强>更新强>
我刚试过你的代码,对我来说它很有效 鉴于您有一个名为timerTextField的IBOutlet连接到Interface Builder中的NSTextField实例,此代码每秒更新一次文本字段:
@interface SSWAppDelegate ()
{
NSUInteger time;
}
@property (weak) IBOutlet NSTextField *timerTextField;
@end
@implementation SSWAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSTimer* timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
- (void)updateTime:(id)sender
{
time += 1;
if((time % 60) <= 9) {
NSString *tempString = [NSString stringWithFormat:@"%lu:0%lu",(time/60),(time%60)];
[self.timerTextField setStringValue:tempString];
} else {
NSString *tempString = [NSString stringWithFormat:@"%lu:%lu",(time/60),(time%60)];
self.timerTextField.stringValue = tempString;
}
NSLog(@"timerTextField: %@", self.timerTextField.stringValue);
}
@end