我想保存开关状态。我创建自定义单元格类打印一个开关标签,但有问题,如果我搜索一些文本然后表视图重新加载和我选择的开关状态将要改变,是否有可能维持该状态?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
....
selectionStyle = UITableViewCellSelectionStyleNone;
CfResultFatch *temp = [result objectAtIndex:indexPath.row];
NSLog(@"%@",temp.complanName);
//[cell.switchOnOff setOn:NO];
[cell.switchOnOff setTag:indexPath.row];
[cell.switchOnOff addTarget:self action:@selector(selectUser:)forControlEvents:UIControlEventValueChanged];
[cell.switchOnOff setTag:indexPath.row];
cell.lblUserName.text = temp.complanName;
cell.textFld.text = temp.cipd;
return cell;
}
//在切换状态改变时调用的selectUser
-(IBAction)selectUser:(UISwitch*)sender{
if(sender.on)
{
[selectedpet addObject:[result objectAtIndex:sender.tag]];
}else{
NSLog(@"%@",sender);
for(int j=0;j<[selectedpet count]; j++)
{
CfResultFatch *temp = [result objectAtIndex:sender.tag];
CfResultFatch *temp1= [selectedpet objectAtIndex:j];
if([(temp.complanName)isEqualToString:(temp1.complanName)]) {
[selectedpet removeObjectAtIndex:j];
}
}
}
}
//并在searchBar中搜索此方法是在搜索某些文本时调用并且数据是从数据库更改的问题在这里是我选择0和1索引然后再搜索一些文本,表视图中的新数据来了0和1索引为ON,如何维护它以及如何获得我以前的Switch状态
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSString *weburl = [NSString stringWithFormat:@"%@%@", @"http://192.168.1.196/ravi/searchUser.php?mname=",searchText];
NSURL *url = [NSURL URLWithString:weburl];
NSData *data =[NSData dataWithContentsOfURL:url];
[self getData:data];
[temptab reloadData];
}
你好。抱歉我的英语不好
答案 0 :(得分:3)
更改后应存储UISwitch
的状态。它可能不是最好的方法,但您可以将状态存储在这样的字典中:
NSMutableDictionary *states = [NSMutableDictionary alloc] init];
[states setObject:[NSNumber numberWithBool:sender.on] forKey:[NSNumber numberWithInt:sender.tag]]
然后,在显示UITableViewCell
:
if ([states objectForKey:[NSNumber numberWithInt:indexPath.row]] != nil)
cell.switchOnOff.on = [[states objectForKey:[NSNumber numberWithInt:indexPath.row]] boolValue]
else
cell.switchOnOff.on = NO;