第一种方式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
cell.textLabel.text = self.data[indexPath.row];
if (self.indexPath == indexPath.row) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// 取出对应的主题名称
NSString *themeName = self.data[indexPath.row];
[ThemeManager shareManager].themeName = themeName;
// 取消选中单元格
[tableView deselectRowAtIndexPath:indexPath animated:NO];
// 如果点击的这行之前点击过一次 直接返回
// if(indexPath.row==self.indexPath) return;
// 1.取得点击的那一行的单元格(旧)
UITableViewCell *oldCell =[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.indexPath inSection:0]];
// 隐藏对号
oldCell.accessoryType = UITableViewCellAccessoryNone;
// 2.取得点击的那一行的单元格(新)
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
// 显示对号
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
// 将点击的行号记录到全局
self.indexPath=indexPath.row;
// 当前点击的行号记录到本地
[[NSUserDefaults standardUserDefaults] setValue:@(self.indexPath) forKey:@"indexPath"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (instancetype)init
{
if (self = [super init]) {
// push后隐藏标签栏
self.navigationController.hidesBottomBarWhenPushed = YES;
// 本地读取数据
self.indexPath = [[[NSUserDefaults standardUserDefaults] objectForKey:@"indexPath"] floatValue];
}
return self;
}
第二种方式
//懒加载获取数据
- (NSArray *)data
{
if (_data == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"theme.plist" ofType:nil];
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
_data = [dic allKeys];
// 每次从字典取值进行排序
_data = [_data sortedArrayUsingSelector:@selector(compare:)];
}
return _data;
}
#pragma mark - 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
cell.textLabel.text = self.data[indexPath.row];
//如果是当前选中的主题,则给辅助图标
NSString *themeName = [ThemeManager shareInstance].themeName;
if ([cell.textLabel.text isEqualToString:themeName]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// 取出对应的主题名称
NSString *themeName = self.data[indexPath.row];
// 设置主题显示
[ThemeManager shareInstance].themeName = themeName;
// 取消选中单元格
[tableView deselectRowAtIndexPath:indexPath animated:NO];
// 刷新数据
[tableView reloadData];
}