В настоящее время я работаю над своим вторым проектом, который фокусируется на CoreData и пользовательских ячейках.Доступ к UISwitch из пользовательской ячейки таблицы
У меня есть пользовательская ячейка с изображением & ярлык & переключатель, я пытаюсь сохранить значение переключателя для userdefaults, когда значение переключателя изменилось. Но я застрял в том, как получить доступ к каждому коммутатору по отдельности (в том же разделе моего представления таблицы есть 2), поэтому, когда нажата кнопка, целое число, сохраненное в userdefaults, мгновенно обновляется.
Это код в .m файле, относящемся к пользовательской ячейке (switchCell), извиняется за любой беспорядочный код и т. Д., Я почти 100% самостоятельно преподаю без каких-либо советов/отзывов о любых ошибках, которые я делаю.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
// Code for the first section, controlling which cells use the custom cell SwitchCell
if (indexPath.section == 0)
{
if(indexPath.row == 1 || indexPath.row == 2)
{
SwitchCell *switchCell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCellIdentifier"];
cell = switchCell;
}
else
{
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"CellIdentifier"];
UISwitch *testSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = testSwitch;
}
}
}
// Each other section currently uses the standard cell type
else
{
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"CellIdentifier"];
}
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dictionary = [settingsTableData objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"Settings"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
SwitchCell *switchCell = (SwitchCell *)cell;
[[NSUserDefaults standardUserDefaults] synchronize];
// Integers to store the on/off state of each switch (2)
NSInteger capsValue = [[NSUserDefaults standardUserDefaults] integerForKey:@"capitalsSwitchOn"];
NSInteger numbersValue = [[NSUserDefaults standardUserDefaults] integerForKey:@"numbersSwitchOn"];
NSLog(@"Upon load capsValue equals : %d", capsValue);
NSLog(@"upon load numbersValue equals : %d", numbersValue);
// Setting individual cell values for attributes such as image and text
if (indexPath.section == 0)
{
if(indexPath.row == 1)
{
switchCell.switchCellLabel.text = cellValue;
switchCell.switchCellImage.image = [UIImage imageNamed:@"capitalsImage.jpg"];
// Set to true or false depending on what you want the default value to be.
//switchCell.switchCellSwitch.on = FALSE;
if (capsValue == 1) {
[switchCell.switchCellSwitch setOn:NO animated:YES];
} else
[switchCell.switchCellSwitch setOn:YES animated:YES];
}
else if (indexPath.row == 2)
{
switchCell.switchCellLabel.text = cellValue;
switchCell.switchCellImage.image = [UIImage imageNamed:@"capitalsImage.jpg"];
if (numbersValue == 1) {
[switchCell.switchCellSwitch setOn:NO animated:YES];
} else
[switchCell.switchCellSwitch setOn:YES animated:YES];
}
else
{
cell.textLabel.text = cellValue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
else if (indexPath.section == 1)
{
if (indexPath.row == 0)
{
cell.textLabel.text = cellValue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
else if (indexPath.row == 1)
{
cell.textLabel.text = cellValue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
else if (indexPath.section == 2)
{
if (indexPath.row == 0)
{
cell.textLabel.text = cellValue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
else if (indexPath.row == 1 || indexPath.row == 2)
{
cell.textLabel.text = cellValue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
}
Заранее благодарим за любую помощь!
Тим почему ты предполагаешь, что он использует раскадровку? :) –
@AuRis он бы назвал 'dequeueReusableCellWithIdentifier: @" SwitchCellIdentifier ", если он не использовал Storyboard или .nib-файл? Я мог ошибаться, но как бы вы определили/построили ячейку для этого Идентификатора, если не через .nib или раскадровку? –
Эй, я использую файлы .nib, так как обучение коду у меня создалось впечатление, что раскадровка - это не путь; следовательно, почему ive избегал их! –