gpt4 book ai didi

ios - 首次显示表格时未显示 UITableViewCell subview

转载 作者:行者123 更新时间:2023-11-28 19:16:38 25 4
gpt4 key购买 nike

我正在尝试向我的表格单元格添加删除线标签(以 BOOL hasStrikethrough 为条件)。问题是第一次显示表格时删除线没有出现(即使 hasStrikethrough == YES)。如果滚动表格,则行会重新显示并且删除线会正确显示。删除线只是作为 UITableViewCell 的 subview 添加的 UILabel。

这是我的 cellForRowAtIndexPath 代码:

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

static NSString *CellIdentifier = @"ItemCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}


Item *item = [self.fetchedResultsController objectAtIndexPath:indexPath];

cell.textLabel.text = item.itemName;
cell.textLabel.textAlignment = UITextAlignmentLeft;
cell.showsReorderControl = YES;
cell.shouldIndentWhileEditing = NO;

if ([[item hasStrikethrough] boolValue] == YES) {
[self addStrikethrough:cell];
}

return cell;
}

这是添加删除线的代码:

- (void)addStrikethrough:(UITableViewCell*)cell
{
CGRect frame = cell.textLabel.frame;
UILabel *strikethrough = [[UILabel alloc] initWithFrame:frame];
strikethrough.opaque = YES;
strikethrough.backgroundColor = [UIColor clearColor];
strikethrough.text = @"------------------------------------------------";
strikethrough.lineBreakMode = UILineBreakModeClip;
[cell addSubview:strikethrough];
}

提前致谢:-)

最佳答案

问题出在行 CGRect frame = cell.textLabel.frame;
单元格的 textLabel 尚未布局,因此框架将为 (0,0,0,0),您不会看到删除线标签。

您在下一个单元格中看到删除线的原因是因为那些是已经布置了 textLabel 的重用单元格。

在我看来,你有两个选择:
第一个选项,自己设置删除线框,你可以使用 sizeWithFont 来确定所需的宽度,字体应该是 textFiled 字体。稍微尝试一下以找到正确的 x 偏移量,以便它正好位于 textLabel 上。

- (void)addStrikethrough:(UITableViewCell*)cell
{
CGSize textLabelSize = [cell.textLabel.text sizeWithFont:[UIFont systemFontOfSize:20.0]];

CGFloat cellHeight = cell.bounds.size.height;
CGFloat strikethroughLabelHeight = 20.0;

CGRect frame = CGRectMake(12, (cellHeight - strikethroughLabelHeight)/2, textLabelSize.width, strikethroughLabelHeight);
UILabel *strikethrough = [[UILabel alloc] initWithFrame:frame];
strikethrough.opaque = YES;
strikethrough.backgroundColor = [UIColor clearColor];
strikethrough.text = @"------------------------------------------------";
strikethrough.lineBreakMode = UILineBreakModeClip;
[cell.contentView addSubview:strikethrough];
}

第二个选项是继承 UITableViewCell 并为其添加删除线标签。
然后你可以在 layoutSubviews 方法中设置它的框架,你可以根据你的需要隐藏/取消隐藏这个标签...

关于ios - 首次显示表格时未显示 UITableViewCell subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11605519/

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