ios - 更新 UITableViewCell 上的标签

标签 ios objective-c uitableview

我有一个 NSTimer 每四秒调用一次这个方法:

- (void)timerDecrement
{
    timerCount = timerCount-1;  
    [OtherViewControllerAccess updateTimeLeftLabel];  
}

updateTimeLeftLabel在另一个类(class):
- (void)updateTimeLeftLabel
{
    int timeLeft = OtherClassAccess.timerCount;

    UILabel *timeLeftLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 10, 120, 20)];
    timeLeftLabel.text = [NSString stringWithFormat:@"Tid kvar: %ih", timeLeft];
    [cell addSubview:timeLeftLabel];
}

基本上我希望我的应用程序在当前剩余时间的情况下更新表格 View 中单元格中的标签,但上述方法对调用没有任何作用。所以我的问题是,如何将此 subview 添加到 cellForRowAtIndexPath: 之外的单元格中委托(delegate)方法,然后让它在每次调用该方法时更新该标签。

最佳答案

So my question is, how can I add this subview to the cell outside the cellForRowAtIndexPath:delegate method, and then make it update that label every time the method is called.



答案是,不要将 subview 添加到 cellForRowAtIndexPath 之外的表格 View 单元格。这些单元格属于表格 View ,您绝对绝对不应该尝试修改它们。这就是表格 View 的工作。

就像代码有问题的一个小例子一样,您将向表格 View 单元格添加越来越多的标签 View ,每 1/4 秒一个。那很糟。

第二点:哪个细胞是“细胞”?表格 View 管理整个单元格表格。如果用户滚动,一些单元格将滚动到屏幕外并替换为不同的单元格。

相反,您应该找出哪个 indexPath 包含包含您的数据的单元格,更改模型中的数据,并告诉您的表格 View 在适当的 indexPath 处更新单元格。这将导致它使用更新的内容重绘。

关于ios - 更新 UITableViewCell 上的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551768/

相关文章:

iphone - 我如何通过应用程序在 iOS 的桌面上创建快捷方式

iphone - NSString 未正确显示

objective-c - 应用程序随机停止接收按键(CGEventTaps)

iphone - iOS uiwebview 回退历史控件

ios - NavigationBar 在运行时隐藏 View ,但不在 Interface Builder 中

ios - objc_msgSend() 传递了 "a pointer to the reciever' s 数据是什么意思?

ios - Researchkit 限制多项选择

ios - 使用 NavController 推送 View 时如何隐藏标签栏?

swift - 以编程方式将对象添加到 UIViewController 和 UITableViewController 的原型(prototype)单元之间有区别吗?

ios - 如何在 uitableview for IOS 中使用 Reusable Cells