gpt4 book ai didi

objective-c - 带有 UILabel subview 缓存问题的 UITableViewCell

转载 作者:行者123 更新时间:2023-11-29 13:32:15 25 4
gpt4 key购买 nike

首先,请不要告诉我这是重复的。我知道这个问题已被多次询问和回答,但即使在阅读了其他人的解决方案之后,我似乎仍然无法让我的代码正常工作。

我的包含 UILabel subview 的 UITableViewCell 出现问题。 UILabel 有时不会出现在某些单元格中,直到我滚动离开这些单元格并返回到它们。这是我用来自定义单元格的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

UILabel *label;

if (cell == nil) {

// cell is nil, create it

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];


label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 33)];
label.tag = 888;

} else {

label = (UILabel*)[cell.contentView viewWithTag:888];
[label removeFromSuperview];

}

label.text = @"Label Text";
label.backgroundColor = [UIColor clearColor];
[label sizeToFit];
label.center = CGPointMake(cell.contentView.frame.size.width-label.frame.size.width/2-20, cell.contentView.frame.size.height/2);
[cell.contentView addSubview:label];

// customize cell text label
cell.textLabel.text = @"Cell Text";
cell.textLabel.textColor = [UIColor darkGrayColor];

return cell;
}

当 dequeueReusableCellWithIdentifier:CellIdentifier 返回非 nil 值时标签似乎正确显示,但如果返回值为 nil 且必须实例化新单元格则标签不显示。

如果有人知道为什么会发生这种情况,将不胜感激。

最佳答案

我看到你想做几件事。

1) 阅读“sizeToFit”——描述中说如果 View 没有父 View ,你可能会得到奇怪的结果。

2) 创建 View 时,立即将其添加到单元格中。

3) 调整单元格大小后,获取它的大小,然后计算合适的框架 - 我建议不要使用“中心”,但我不知道你的代码实际上不起作用。

4) 在更改中心以更改框架之前,硬编码如下内容:

CGRect r = label.frame;
r.origin = (CGPoint){ 20, 20 };
label.frame = r;

这至少会让您确信新电池和旧电池都在正常工作。然后你可以计算你真正想要的框架,或者进一步玩中心。

关于objective-c - 带有 UILabel subview 缓存问题的 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11569187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com