iOS UITableViewCell高亮效果实现

需求:点按某个Cell的时候cell上面的文字高亮或者改变颜色
在具体的Cell中重写函数:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{//重写高亮函数
    if (highlighted) {
        self.textLabel.backgroundColor = [UIColor yellowColor];
        self.textLabel.textColor = [UIColor redColor];
        self.textLabel.text = [NSString stringWithFormat:@"这是第%ld行   点中我啦哈哈哈",(long)self.tag];
    }else{
        self.textLabel.backgroundColor = [UIColor clearColor];
        self.textLabel.textColor = [UIColor blackColor];
        self.textLabel.text = [NSString stringWithFormat:@"这是第%ld行   哈哈哈",(long)self.tag];
    }
}

还有一种暴露出来的方式,但是并不推荐,以为每次都会调用tableView cellForRowAtIndexPath:indexPath
方法如下:
在ViewController实现

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor yellowColor];
    //cell.contentView.backgroundColor = [UIColor greenColor];
}
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor blackColor];
    //cell.contentView.backgroundColor = [UIColor grayColor];
}```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容