需求如标题, 实现方法如下:
在didSelectRow中进行如下设置:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.selectedBackgroundView = [[UIView alloc]initWithFrame:cell.bounds];
cell.selectedBackgroundView.backgroundColor = [UIColor colorWithHexString:@"0095d9"];
}
这样我们实现了第一个需求,在点击的时候,会显示自定义的颜色,而不是系统的颜色.
接下来实现第二个需求,在你请求完数据,进行reloadData之后, 添加如下方法:
[_mainTableView.mj_header endRefreshing];
[_mainTableView reloadData];
//表视图进行了刷新
//设置你想选中的某一行,我这里是第一行
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//执行此方法,表明表视图要选中这一行
[_mainTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
//调用此方法,显示我们自定义的选中颜色
[self tableView:_mainTableView didSelectRowAtIndexPath:indexPath];
总结: 以前也做过这个需求,但由于时间比较久,并且之前好像还有bug,所以有重新整理做了一次;
这次实现的方式比较官方,没有自定义视图 ,都是使用系统的方法;
didSelected方法改变了cell的 selected属性,为YES,在官方文档中: 直接设置这个属性对cell的选中状态是没有用的;
要默认某一行,直接执行 :
[self tableView:_mainTableView didSelectRowAtIndexPath:indexPath]
是不起作用的;
要先执行:
[_mainTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
再执行选中方法,就可以实现了;
但具体的原理,我还不是很明白,仍然需要学习; 请不吝赐教;