今天在為tableViewCell設(shè)置點擊改變cell.textLabel.text的顏色,
方法有兩種
<1>通過指針找到點擊的cell
//將左側(cè)的UITableView設(shè)置為全局變量
#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
{
//左側(cè)leftView
_leftView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 120, RECT.size.height) style:UITableViewStylePlain];
[self.view addSubview:_leftView];
_leftView.dataSource = self;
_leftView.delegate = self;
//注冊的方式設(shè)置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];
}
//關(guān)鍵是這里,通過指針cell找到被點擊的對象,在點擊事件中改變其顏色,在點擊事件取消中,將顏色變回黑色.
// ? cellForRowAtIndexPath: ? ?這個方法找通過創(chuàng)建指針找到當(dāng)前被點擊的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>還有一種方法是在創(chuàng)建cell的時候可以將cell存放在數(shù)組中,在點擊事件中對數(shù)組的元素進(jìn)行操作.