【发布时间】:2011-03-25 00:19:40
【问题描述】:
免责声明:我是 iOS 的新手,所以请随时告诉我,我的整个方法都是错误的。我只要求您解释原因——我的目标是学习(当然,也是为了解决这个问题)。
...
大家好,我是 iOS 编程新手,在尝试解决这个问题几个小时后,我的无知和可可缺乏经验正在成为我的最佳选择。希望我能在这里找到一些帮助。
我正在开发一个简单的 TableView 应用程序,作为一个正在开发中的大型应用程序的沙盒。我现在想要实现的功能是对 TableView Cell 中的字幕文本进行伪实时更新(即 cell.detailTextLabel.text )。
为了让您更好地了解目标:我正在努力做到这一点,以便用户可以点击 TableView 单元格,并且“秒表”样式的计时器开始在字幕文本中计数。
但我也不知道如何更新 cell.detailTextLabel.text A)从我的计时器方法内部(它说 tableView 未声明)和 B)以反复刷新单元格的方式,以便用户看到“活动" 计时器。
所以,这里有一些代码(现在所有这些都在 RootViewController 中。最终我想为像计时器这样的函数创建单独的类,但我只想让事情先工作)。
我还应该补充一点,我现在在这个类中有很多全局(“接口?”)变量。它使实验更容易,但如果这可能导致一些问题,请告诉我。我仍在学习如何来回传递对象/变量/等。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
self.runTimerFunctions;
}
然后是定时器函数(那些是接口变量):
- (void) runTimerFunctions {
start = CFAbsoluteTimeGetCurrent();
timerRunning = YES;
timer = [NSTimer scheduledTimerWithTimeInterval: 0.01 target:self selector:@selector(targetMethod:) userInfo:nil repeats:YES];
}
数学和计算本身。生成格式为 MM:SS.hh 的单个字符串“liveTimer”,该字符串准确地向上“秒表”:
- (void)targetMethod: (NSTimer *)theTimer {
// NOTE TO SELF -- right now I've got hours, minutes, seconds, etc as global variables. But that may be unnecessary.
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime timeDelta = end-start;
int integerSecs = timeDelta;
int integerCentiSecs = timeDelta * 100;
hundredths = integerCentiSecs % 100;
NSString *hundredthsString = [NSString stringWithFormat:@"%02i", hundredths];
seconds = integerSecs % 60;
NSString *secondsString = [NSString stringWithFormat:@"%02i", seconds];
minutes = (integerSecs / 60) % 60;
NSString *minutesString = [NSString stringWithFormat:@"%02i", minutes];
// Now combine these value strings into the single liveTimer string
liveTimer = [NSString stringWithFormat:@"%@:%@.%@", minutesString, secondsString, hundredthsString];
}
好的,所以 liveTimer 字符串是一个接口变量,所以我可以修改它并在整个过程中访问它(这可能不是这样做的方法,我还是个菜鸟,所以请在必要时纠正我)。
在最初的UITableViewCell创建位中,我使用liveTimer作为detail text value,如下:
cell.textLabel.text = @"Name";
NSLog(@"liveTimer value is %@", liveTimer);
cell.detailTextLabel.text = liveTimer;
基本上,就我现在的情况而言,当用户按下列表项时,计时器开始在后台计数(我已经通过 NSLog 确认它工作正常——如果我在 targetMethod 的末尾提取了 liveTimer,它的格式正确并向上计数。
但是如何通过单元格文本的伪实时更新来反映这一点?
[tableView reloadData] 当我将它放在任何我可以的地方时,它会不断使程序崩溃(没有错误代码),但我不知道如何从 targetMethod 访问它(它告诉我 tableView 在我添加 [tableView reloadData] 时未声明) .
此外,[tableView reloadData] 一直在使程序崩溃(没有错误消息),即使我尝试将其放入didSelectRowAtIndexPath 中也是如此。例如
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
self.runTimerFunctions;
[tableView reloadData];
基本上我确信有一种简单的方法可以做我想做的事情,但我对这门语言还太陌生,不知道该怎么做。如果我通过在计时器循环期间尝试调用 reloadData 来使系统超载,我不会感到惊讶。但话又说回来,也许是别的东西。
任何建议将不胜感激。我正在尝试在这里学习语言,虽然示例代码非常有帮助,但我对“学习如何钓鱼”同样感兴趣,所以我非常感谢为什么我的解释我做错了,还有什么更好的方法,等等。
提前感谢您的帮助;我期待参与论坛。
【问题讨论】:
标签: objective-c cocoa-touch xcode ios