Я делаю телефонную книгу.Как создать UITableView, полный UITableViewCells, каждый с UISwitch?
Я пытаюсь создать UITableView, в котором есть ячейка прототипа, которая содержит UISwitch, который описывает, является ли конкретный контакт общедоступным или приватным.
Как это создать, чтобы UISwitch сохранял статус переключения даже во время прокрутки? dequeueReusableCellWithIdentifier
дает мне много проблем в том, что он не сохраняет togglestate из UISwitches.
Хотя я люблю экономию памяти, переключая переключатели внутри cellForRowAtIndexPath (в соответствии с логическим значением конфиденциальности для контакта) не работает, чтобы всегда показывать публичный/частный статус контакта.
См скриншот ниже того, что я пытаюсь построить:
EDIT: Вот мой 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";
[email protected]"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;
}
ВТОРОЙ EDIT: Вот мой метод "togglePublic", который работает на «valueChanged» переключателя
-(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];
}];
}
Настройка состояния переключателя в 'cellForRow ...' является допустимым подходом. Если он не работает, вы делаете что-то неправильно. Отправьте свой метод cellForRow .... – rmaddy
@rmaddy просто добавил изменения - дайте мне знать, что вы думаете! – Rohan
Код отображается правильно. Возможно, проблема связана с изменением значения переключателя. У вас есть код, который отвечает на изменение коммутатора пользователем, а затем обновляет запись 'AHBContact' с новым значением? – rmaddy