I'm making a phonebook.
I'm trying to create a UITableView that has a prototype cell in it that contains a UISwitch which describes if a particular contact is public or private.
How can I create this such that the UISwitch keeps its toggle status even during scroll? dequeueReusableCellWithIdentifier
is giving me a lot of problems in that it doesn't save the togglestate of the UISwitches.
Though I love the memory savings, toggling the switches within cellForRowAtIndexPath (according to a contact's privacy boolean value) is not working to always display the public/private status of a contact.
See screenshot below of what I'm trying to build:
EDIT: Here's my cellForRowAtIndexPath:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
AHBContact *thisContact = nil;
AHBBrowseContactCell *cell =[tableView dequeueReusableCellWithIdentifier:@"BROWSECELL"];
// from contacts list
thisContact = [self.contacts[indexPath.section] allValues][0][indexPath.row];
cell.customPublicSwitch.onTintColor = [AHBUtilities greenColor];
cell.customPublicSwitch.onText= @"Public";
cell.customPublicSwitch.offText=@"Private";
if(thisContact.privacy){
NSLog(@"public %@",thisContact.fullName);
cell.customPublicSwitch.on = YES;
}
else{
NSLog(@"private %@", thisContact.fullName);
cell.customPublicSwitch.on = NO;
}
cell.labelName.text = thisContact.fullName;
cell.labelName.font = [AHBUtilities regularFontWithSize:cell.labelName.font.pointSize];
cell.imageViewIcon.image = [AHBIcons phoneIconForCategory:thisContact.category];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.backgroundColor = [UIColor colorWithWhite:1 alpha:0.55];
return cell;
}
SECOND EDIT: Here's my "togglePublic" method that runs on "valueChanged" of the switch
-(IBAction)togglePublic:(UIControl *)button withEvent:(UIEvent *)event {
DCRoundSwitch *switch1 = (DCRoundSwitch *)button;
UITableViewCell *cell = (UITableViewCell *)switch1.superview;
NSIndexPath *indexPath = [self.tableview indexPathForCell: cell.superview];
if ( indexPath == nil ){
return;
}
AHBContact *contact = [self.contacts[indexPath.section] allValues][0][indexPath.row];
contact.privacy = !contact.privacy;
NSLog(@"Public switch toggled for: %@", contact.firstName);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[[AHBContactsController sharedController] updateContact:contact completion:^(id result) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSLog (@"Public/Private updated%@",result);
} failure:^(NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Sync Problem"
message:@"Could save changes. Please try again."
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[message show];
}];
}