今天在为tableViewCell设置点击改变cell.textLabel.text的颜色,
方法有两种
<1>通过指针找到点击的cell
//将左侧的UITableView设置为全局变量
#define RECT [UIScreen mainScreen].bounds
@interface EnterPagerViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) UITableView *leftView;
@property (nonatomic,strong) NSArray *cellName;
@end
#pragma mark UI
- (void)createUI
{
//左侧leftView
_leftView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 120, RECT.size.height) style:UITableViewStylePlain];
[self.view addSubview:_leftView];
_leftView.dataSource = self;
_leftView.delegate = self;
//注册的方式设置cell
[_leftView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}
#pragma mark tableDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _cellName.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *ident = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
cell.textLabel.text = _cellName[indexPath.row];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.textLabel.font = [UIFont systemFontOfSize:20];
return cell;
}
#pragma mark tableDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == _rightView)
{
[_rightView reloadData];
}
//关键是这里,通过指针cell找到被点击的对象,在点击事件中改变其颜色,在点击事件取消中,将颜色变回黑色.
// cellForRowAtIndexPath: 这个方法找通过创建指针找到当前被点击的cell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.textColor = [UIColor greenColor];
cell.textLabel.backgroundColor = [UIColor whiteColor];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.backgroundColor = [UIColor grayColor];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}
<2>还有一种方法是在创建cell的时候可以将cell存放在数组中,在点击事件中对数组的元素进行操作.