ios - 自定义一个 UITableViewCell 高亮样式

标签 ios uitableview

我对如何自定义 UITableViewCell 突出显示样式感到困惑,不仅是突出显示的单元格背景颜色,还包括其 subview ( ImageView )的框架?

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated

方法对我不起作用。如果我只更改单元格的突出显示颜色,效果会很好。但它不适用于更改单元格 subview 的框架。

感谢您的帮助!

最佳答案

你可以通过下面的方式做到这一点

下面是它的示例代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *strIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(278, 2, 40, 40)];
    [imgv setBackgroundColor:[UIColor grayColor]];
    imgv.tag = 100 + indexPath.row;
    [cell.contentView addSubview:imgv];

    [cell.textLabel setText:[NSString stringWithFormat:@"Cell: %d",indexPath.row]];
    [cell.detailTextLabel setText:[NSString stringWithFormat:@"%03d - %03d",indexPath.section, indexPath.row]];

    return cell;
}

-(void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell.textLabel setBackgroundColor:[UIColor orangeColor]];

    //set the frame of subview on highlight
    UIImageView *imgv = (UIImageView*)[cell.contentView viewWithTag:100+indexPath.row];
    [imgv setBackgroundColor:[UIColor orangeColor]];
    [imgv setFrame:CGRectMake(238, 2, 80, 40)];
}

-(void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell.textLabel setBackgroundColor:[UIColor clearColor]];

    //now reset the frame of subview on Unhighlight
    UIImageView *imgv = (UIImageView*)[cell.contentView viewWithTag:100+indexPath.row];
    [imgv setBackgroundColor:[UIColor grayColor]];
    [imgv setFrame:CGRectMake(278, 2, 40, 40)];
}

关于ios - 自定义一个 UITableViewCell 高亮样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25277048/

相关文章:

iOS8 - 如何在 iOS 8 中更改长按手势的灵敏度

javascript - 如何在 React Native 上获取 IDFA 和 ADID?

ios - 在我按下开始游戏后为我的 NSTimer 添加延迟

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

ios - JSON 数据未加载到 UITableView 中

ios - 如果连接了硬件键盘,则隐藏 inputAccessoryView

iphone - 等待结果而不停止 UI

ios - “scrollViewDidScroll”无法连续捕获移动

ios - 如何在 Xamarin iOS 中为 UITableViewCell 从底部到顶部的过渡设置动画?

objective-c - 将数组写入 plist 并填充 tableview