gpt4 book ai didi

ios - 在 UITableViewCell 中有条件地显示图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:18:19 26 4
gpt4 key购买 nike

我试图仅在 UITableView 的某些单元格中显示图像。这是我的 configureCell 方法:

-(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
StoryInfo *info = [self.fetchedResultsController objectAtIndexPath:indexPath];
UIImage *ribbon = [UIImage imageNamed:@"ribbon.png"];
UIImageView *ribbonView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
[ribbonView setImage:ribbon];
[cell addSubview:ribbonView];
if([[NSNumber numberWithBool:NO] isEqualToNumber:info.visited]) {
cell.textLabel.textColor = [UIColor colorWithRed:53/255.0 green:53/255.0 blue:52/255.0 alpha:1];
ribbonView.hidden = NO;
}
else {
cell.textLabel.textColor = [UIColor colorWithRed:128.0/255.0 green:128.0/255.0 blue:128.0/255.0 alpha:1.0];
ribbonView.hidden = YES;
}
}

这里是 cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// set up the cell...
[self configureCell:cell atIndexPath:indexPath];

return cell;
}

这不太有效,因为一开始,所有单元格都将它们绘制为 ribbonView,而不管 info.visited 的值如何。我已经通过了 if/else,但我看到隐藏代码被击中了。但是,如果我离开列表,然后返回,则可以看到正确的功能区状态。滚动表格 View 会再次破坏它。

不过,字体颜色总是正确的。

最佳答案

如果您要重复使用单元格,则可能是您要添加多个 ribbonView单元格的 subview ,所以即使 info.visited当前 indexPathNO ,您仍然可以看到单元格上剩余的另一个 ribbonView。

要做的就是确保你只有一个ribbonView subview ,可以通过删除旧的 ribbonViews 来完成在你的配置方法中,或者通过子类化更好 UITableViewCell并添加 ribbonView单元格的属性,设置一次并添加到单元格的 View 层次结构一次,然后您可以访问和设置 hiddenNOYES在配置方法中。

编辑:单元格文本颜色将始终正确,因为您正在更改 UILabel 的一个实例的颜色这是在单元格的 View 层次结构中。如果您的配置方法添加了一个新的 UILabel,我希望您会看到相同的错误行为。每次配置时都对单元格进行 subview 。

编辑:代码尝试

-(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
static NSInteger ribbonTag = 12345;
StoryInfo *info = [self.fetchedResultsController objectAtIndexPath:indexPath];
// re-use a ribbonView if one's already been added to this cell
UIImageView *ribbonView = [cell.contentView viewWithTag:ribbonTag];
if (!ribbonView){
ribbonView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
ribbonView.tag = ribbonTag;
UIImage *ribbon = [UIImage imageNamed:@"ribbon.png"];
[ribbonView setImage:ribbon];
// add subviews to contentView
[cell.contentView addSubview:ribbonView];
}
if([[NSNumber numberWithBool:NO] isEqualToNumber:info.visited]) {
cell.textLabel.textColor = [UIColor colorWithRed:53/255.0 green:53/255.0 blue:52/255.0 alpha:1];
ribbonView.hidden = NO;
}
else {
cell.textLabel.textColor = [UIColor colorWithRed:128.0/255.0 green:128.0/255.0 blue:128.0/255.0 alpha:1.0];
ribbonView.hidden = YES;
}
}

关于ios - 在 UITableViewCell 中有条件地显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15451469/

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