功能需求一:头一次进来时默认选择第一个cell
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"测试";
self.view.backgroundColor = [UIColor whiteColor];
// 默认选择第一个cell
[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
}
tableview的数据源方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"tableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
if (indexPath.row == 0) {
cell.textLabel.textColor = [UIColor blackColor];
} else {
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
}
cell.textLabel.text = @"测试";
return cell;
}
tableview的代理方法
// 点击cell--取消上一次选择的cell
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.textColor = [UIColor whiteColor];
if (indexPath.row == 0) {
cell.backgroundColor = [UIColor blackColor];
}
}
// 点击cell--本次选择的cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.textColor = [UIColor blackColor];
}
即可实现tableview的单选cell字体和背景动态变化的功能