实现点击cell实现改变cell和cell上控件的背景颜色

话不多少,贴上代码吧!!!

//
//  ViewController.m
//  CellChangeBgColorDemo
//
//  Created by 思 彭 on 17/1/12.
//  Copyright © 2017年 思 彭. All rights reserved.
//

#import "ViewController.h"
#import "TableViewCell.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    // 注册cell
    [self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 10;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.titleLabel.text = [NSString stringWithFormat:@"%ld--%ld",indexPath.section,indexPath.row];
    cell.contentView.backgroundColor = [UIColor lightGrayColor];
    cell.selectedBackgroundView = [[UIView alloc]initWithFrame:cell.frame];
    cell.selectedBackgroundView.backgroundColor = [UIColor orangeColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
//    NSIndexPath *selectIndexPath = [self.tableView indexPathForSelectedRow];
//    NSLog(@"selectIndexPath = %ld---%ld",selectIndexPath.section,selectIndexPath.row);
    TableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.titleLabel.backgroundColor = [UIColor redColor];
    cell.contentView.backgroundColor = [UIColor orangeColor];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

@end

 

posted on 2017-01-12 13:42  玉思盈蝶  阅读(276)  评论(0编辑  收藏  举报

导航