1

Я работаю с UICollectionView, и у меня есть немного сложности, повторяя то, что я работаю в UITableView. Я хочу установить selectedBackgroundView ячейки selectedUICollectionView и сохранить этот выбор при каждом просмотре представления.Настройка выбранногоСекретальный просмотр UICollectionViewCell при перезагрузке представления

У меня есть базовое приложение с двумя вкладками в Tab Bar controller, где обе вкладки: UITableViewControllers. Вторая вкладка - это настройки In-App, и у меня есть два cells; один для приложений и один для темы «Клавиатура». Темы клавиатуры - еще один Table View, но App Themes - это UICollectionView с сеткой из 3x4 ячеек. Хотя это динамически создается, больше не будет клеток, и это все.

Работа

Прямо сейчас, я могу выбрать UICollectionViewCell и счастливо применять пользовательское изображение на верхней части; это работает очень хорошо.

Проблема

Проблема я столкнулся заключается в том, что выбранная ячейка не поддерживает, что пользовательское изображение на вершине, когда вид перезагружается, даже если значение сохраняется в NSUserDefaults.

Поскольку у меня такая же концепция, что и мои темы с клавиатурой (UITableView), я скопировал принципы здесь, но не уверен, действительно ли то, что я сделал, действительно правильно.

Вот код:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    ThemeCell *themeCell = (ThemeCell *)[self.cView cellForItemAtIndexPath:indexPath]; 

    self.selectedThemeString = themeCell.cellLabel.text; 

    if(self.checkedIndexPath) 
    { 
     UICollectionViewCell *uncheckCell = [self.cView cellForItemAtIndexPath:self.checkedIndexPath]; 

     uncheckCell.selectedBackgroundView = nil; 
    } 
    themeCell.selectedBackgroundView = dot; 
    [themeCell addSubview:dot]; 

    self.checkedIndexPath = indexPath; 

    UIImageView *dot = [[UIImageView alloc]initWithFrame:CGRectMake(5, 0, 1, 2)]; 
    dot.image=[UIImage imageNamed:@"check-white-hi.png"]; 

    themeCell.selectedBackgroundView = dot; 
    [themeCell addSubview:dot]; 

    [[NSUserDefaults standardUserDefaults] setObject:self.selectedThemeString forKey:@"Selection"]; 

    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 

В cellForItemAtIndexPath, у меня есть:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 

    ThemeCell *themeCell = (ThemeCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Theme Cell" forIndexPath:indexPath]; 

    NSString *cellData = [self.themeLabels objectAtIndex:indexPath.row]; 

    themeCell.cellLabel.text = cellData; 
    themeCell.cellImages.image = self.themeImages[indexPath.row]; 
    UIImageView *dot = [[UIImageView alloc]initWithFrame:CGRectMake(5, 0, 1, 2)]; 
    dot.image=[UIImage imageNamed:@"check-white-hi.png"]; 

    self.selectedThemeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"Selection"]; 

    NSLog(@"Selected Theme String = %@", self.selectedThemeString); 

    if (!self.selectedThemeString) 
    { 
     NSLog(@"111"); 

     self.checkedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
     themeCell.selectedBackgroundView = dot; 
     [themeCell addSubview:dot]; 

    } 
    if ([self.selectedThemeString isEqualToString:@"Original"]) 
    { 
     NSLog(@"222"); 
     self.checkedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
     themeCell.selectedBackgroundView = dot; 
     [themeCell addSubview:dot]; 
    } 
    if ([self.selectedThemeString isEqualToString:@"Mystical"]) 
    { 
     NSLog(@"333"); 
     self.checkedIndexPath = [NSIndexPath indexPathForRow:2 inSection:0]; 
     themeCell.selectedBackgroundView = dot; 
     [themeCell addSubview:dot]; 
    } 

return themeCell; 

Мои viewWillAppear имеет:

self.selectedThemeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"Selection"]; 

if ([self.selectedThemeString isEqualToString:@"Original"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Peacock"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:1 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Mystical"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:2 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Zebra"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:3 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Simplicity"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:4 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Rainbow"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:5 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Prosperity"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:6 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Leopard"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:7 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Hypnotic"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:8 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Dunes"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:9 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Twirl"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:10 inSection:0]; 
} 
else if ([self.selectedThemeString isEqualToString:@"Oceanic"]) 
{ 
    self.checkedIndexPath = [NSIndexPath indexPathForRow:11 inSection:0]; 
} 


[self.cView reloadData]; 

Порядок ячеек определены выше, так первая ячейка первой строки называется оригиналом. Вторая ячейка первой строки называется павлин и третья ячейка первой строки называется Мистическая и т.д.

Мое мышление было, я мог бы определить indexPathForRow для каждой строки и в cellForItemAtIndexPath, когда строка хитов, она будет применяться selectedBackgroundView к изображению.

Статус

Что происходит сейчас есть, я могу успешно выбрать ячейку и появится изображение; если я перезагружу представление (выйдя и вернувшись), selectedBackgroundView из ячейки не существует. Тем не менее, я знаю, что NSUserDefaults работает, потому что в моем cellForItemAtIndexPath «111» или «222» или «333» успешно регистрируются, но он просто не устанавливает состояние подсветки выбранного UICollectionCell.

Что я требую, чтобы:

1) Иметь выбранную ячейку отображения selectedBackgroundView изображения, когда точка зрения была перезагружена.

Update: В cellForItemAtIndexPath, если я ставлю themeCell.backgroundView = dot вместо themeCell.selectedBackgroundView = dot, когда я перезагрузить мнение, каждое отдельное мелирование ячейки с пользовательским изображением, а не только в выбранной ячейке, так что я думаю, что я делаю успехи несколько, но все же потерян.

Любое руководство будет действительно оценено.

ответ

0

Ситуация предотвращена.

Я исправил эту проблему.

Для справки я поставлю фиксированный код здесь для тех, кто испытывает ту же проблему.

В cellForItemAtIndexPath, я сделал следующее:

if (!self.selectedThemeString) 
    { 
     NSLog(@"111"); 

     self.checkedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
     themeCell.backgroundView = dot; 
     [themeCell addSubview:dot]; 
    } 

    if([self.checkedIndexPath isEqual:indexPath]) 
    { 
     NSLog(@"Loaded"); 
     themeCell.backgroundView = dot; 
     [themeCell addSubview:dot]; 

    } 
    else 
    { 
     NSLog(@"Not Loaded"); 

     themeCell.backgroundView = nil; 
    } 

Это похоже на код выше, но по существу скопированы из моего UITableView кода, который проверяет indexPath.

Другое изменение заключается в том, что я использовал свойство backgroundView, а не selectedBackgroundView.

Я сделал это изменение на протяжении всего моего класса, поэтому, где бы у меня не было selectedBackgroundView, я изменил его на backgroundView.

Я счастлив, и это работает как удовольствие.

Смежные вопросы