我的当前应用程序出现问题。它在UITableView
中有一个UIViewController
。我底部有一个UIButton
(UITableView
之外)。它以这种方式工作:
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"bla"]) {
[[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"bla"];
[tableView reloadData];
} else {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"tasks2do"];
[tableView reloadData]; }
当我以这种方式使用cell.textLabel.text
方法时,这很有效:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ident = @"indet";
cell = [tableView dequeueReusableCellWithIdentifier:ident];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease];
}
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"bla"]) {
cell.textLabel.text = [firstArray objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [secondArray objectAtIndex:indexPath.row];
}
return cell; }
现在我想使用UILabel
代替cell.textLabel
,因为我出于某些原因需要它(例如设置标签框)
为此,我使用了以下代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ident = @"indet";
cell = [tableView dequeueReusableCellWithIdentifier:ident];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease];
}
UILabel *thislabel = [[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 250, 44)] autorelease];
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"bla"]) {
[thislabel setText:[firstArray objectAtIndex:indexPath.row]];
} else {
[thislabel setText:[secondArray objectAtIndex:indexPath.row]];
}
[cell.contentView addSubview:thislabel];
return cell; }
这很好,直到我按UIButton
进行切换。它切换,单元格显示新文本,但新文本后面仍旧是旧文本,如下所示:
(firstArray包含字母L,secondArray包含字母J,它混合起来)
你有任何想法解决这个问题,因为我尝试了一些东西(例如使用2 UILabel
s作为数组并隐藏一个)?会很酷。 :)
我希望我的英语不易理解,我的写作英语技能不是最好的,对不起。
如果您需要更多信息/代码发布,不应该是一个问题。
答案 0 :(得分:0)
我建议您创建一个UITableViewCell子类,在其中配置标签(设置框架并将其添加为UITableViewCell初始化程序中的子视图)。添加一个属性来设置标签中的文本,并为属性写一个这样的setter:
- (void)setLabelText:(NSString *)newLabelText
{
if ([self.labelText isEqualToString:newLabelText]) return;
[labelText autorelease];
labelText = [newLabelText copy];
self.label.text = labelText;
[self.label setNeedsDisplay]; // or perhaps [self setNeedsDisplay];
}
编辑:顺便说一下,您正在处理的问题是缓存。每次进入视图时,您都会重新创建一个新标签,即使该单元格之前已经有过标签。发生这种情况是因为您在UITableViewCell初始化程序之外初始化UILabel(对于每个缓存的单元格应该只调用一次,之后可以从缓存中检索它,包括它的所有子视图)。