objective-c - 在 UITableView Objective-C 中的每一行附近添加标签颜色

标签 objective-c ios uitableview

我有一个包含不同部分和行的 UITableView。我想用不同的标签或图像(如图标)关闭每个单元格,但我不知道为什么它看起来像这张图片:

滚动也改变了标签的大小!

代码如下:

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

NSString *key = [[self sectionKeys] objectAtIndex:[indexPath section]];
NSArray *contents = [[self sectionContents] objectForKey:key];
NSString *contentForThisRow = [contents objectAtIndex:[indexPath row]];

static NSString *CellIdentifier = @"CellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  
reuseIdentifier:CellIdentifier];
}
if(indexPath.row == 0)
{
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(3,0,40,40)];
    label.backgroundColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:label];

}
else if(indexPath.row == 1)
{
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(3,0,40,40)];
    label.backgroundColor = [UIColor redColor];
    [cell.contentView addSubview:label];    }
else if(indexPath.row == 2)
{
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(3,0,40,40)];
    label.backgroundColor = [UIColor redColor];
    [cell.contentView addSubview:label];    }
else{

}
[[cell textLabel] setText:contentForThisRow];
return cell;
}

最佳答案

在您的代码中,当用户滚动表格时,标签创建了很多次!您必须检查颜色标签是否已存在于单元格中,然后设置颜色

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
int colorLabelTag = 9999;
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  
                                  reuseIdentifier:CellIdentifier];     
}

// Because table cells are reusing we must check is label already in cell
UILabel* label = (UILabel *) [cell viewWithTag:colorLabelTag];
// If no - we create label
if (!label) {
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(3,0,40,40)];
    label.tag = colorLabelTag;
    [cell addSubview:label];
}

if(indexPath.row == 0)
{
    label.backgroundColor = [UIColor darkGrayColor];        
}
else if(indexPath.row == 1)
{
    label.backgroundColor = [UIColor redColor];
}
else if(indexPath.row == 2)
{
    label.backgroundColor = [UIColor redColor];
}
[[cell textLabel] setText:contentForThisRow];
return cell;

关于objective-c - 在 UITableView Objective-C 中的每一行附近添加标签颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11841872/

相关文章:

ios - 在 cellForRowAtIndexPath 中执行计算是否繁重?

ios - NSInternalInconsistencyException tableView 行删除

objective-c - 如何确保在应用程序终止时调用您的 dealloc 代码?

objective-c - CATransition 从顶部 curl 页面

iOS UIScrollView 中的 UIImageView

ios - 在同一项目中同时使用 Realm Swift 和 Realm Objective-C

ios - UITableViewDelegate 在 iOS 中是否有类似 tableViewWillEndDisplayingCell 的方法?

iphone - 将标签数据从一个 View Controller 传递到另一个 View Controller

ios - 在 UITextView 中将框架高度设置为零

ios - 让iOS应用程序再次接收VoIP推送通知