ios - 根据计时器调整表格 View 单元格文本

标签 ios uitableview nstimer

我正在尝试根据计时器更新单元格的内容。当 View 加载并且计时器启动时。计时器是一个倒计时计时器,每个表格 View 单元格文本应根据计时器更改。计时器是倒数计时器。

-(void)updateLabel{
if(counterValue == 0){
    [self killTimer];
}

    CountdownTableViewMainCell * cell = [self.countdownTableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:0];//i cant get it to work on one cell (the goal is to get it to work on all cells)
    cell.countdownLabel.text = [NSString stringWithFormat:@"%d", counterValue];

   counterValue--;

}

CountdownTableViewMainCell.h

@interface CountdownTableViewMainCell : UITableViewCell

@property (nonatomic,strong) UILabel * countdownLabel;
@property (nonatomic,strong) UILabel * minsLabel;

@end

CountdownTableViewMainCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.countdownLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 21, 21)];
        self.countdownLabel.text = @"14";
        self.countdownLabel.font =[UIFont systemFontOfSize:16.0];
        self.countdownLabel.adjustsFontSizeToFitWidth = YES;

        [self.contentView addSubview:self.countdownLabel];

问题是 self.countdownLabel 没有更新。我已经记录了 counterValue 并且它按预期工作。

最佳答案

在 UITableViews 中,您更新 tableView:cellForRowAtIndexPath 上的单元格内容。 dequeueReusableCellWithIdentifier: 只会从 UITableView 维护的单元格队列中为您获取一个新单元格。它不会为您提供当前显示的 UITableViewCell。

来源:UITableView docs

Call this method from your data source object when asked to provide a new cell for the table view.

您应该做的是在您的 View Controller 上为计数器值维护一个属性。

@property NSInteger counterValue;

在计时器调用的方法中更新该属性。然后重新加载您的 tableView:

self.counterValue--
[self.countdownTableView reloadData]

在您的 tableView:cellForRowAtIndexPath: 中,您可以执行以下操作:

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  //Load cell
  ...
  cell.countDownLabel = [NSString stringWithFormat:@"%d", self.counterValue];
}

这应该在每次调用计时器方法时更新倒计时标签。

关于ios - 根据计时器调整表格 View 单元格文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23473139/

相关文章:

geni.com 的 JSON 身份验证

ios - Swift:尝试与 Web API 通信时出错

ios - 如何使用asiformdatarequest上传图片

ios - AVAudioPlayer 播放完毕时切换桌面 View 单元格图像

iphone - objective-c : Timer crashes app when turned on a second time

ios - 我怎样才能像音乐播放器一样制作倒数计时器?

c# - 安装配置文件服务 - 配置文件安装失败(从 iOS 获取 UDID)

iphone - 分组 UITableView 中节标题和第一个单元格之间的透明像素行

ios - 使用多线程为 UITableViewCell 下载图像,但在滚动 UITableView 之前无法加载图像

objective-c - NSTimer 没有及时触发