UITableView Ячейки Аксессуары меняются при возврате к таблице из другого TableView (через NavController) - PullRequest
1 голос
/ 13 мая 2011

Надеюсь, кто-нибудь сможет мне помочь.

У меня есть контроллер навигации для нескольких контроллеров таблиц. Одно из представлений таблицы («таблица привязок») имеет ячейки с дополнительными представлениями (переключатели и ползунки).

'Таблица привязок' загружается нормально, однако, когда я помещаю новый viewController в стек, а затем возвращаюсь к 'таблице привязок', некоторые ячейки, которые ранее не имели дополнительных представлений, теперь имеют переключатель или ползунок .

В методе viewDidLoad для anchorsViewController я установил переменные экземпляра для переключателей, а ползунки = nil. Вот мой метод cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"Anchors"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;


// Create UI Elements only once by checking to see if
// one of them is nil
if (displayAnchorsSwitch == nil) {      

    // Display Anchors
    if (indexPath.section == 0) {
        NSLog(@"Creating displayAnchorsSwitch");
        self.displayAnchorsSwitch = [[[UISwitch alloc]
                initWithFrame:CGRectZero]autorelease];
        self.displayAnchorsSwitch.on = NO;
        cell.accessoryView = self.displayAnchorsSwitch;

        [self.displayAnchorsSwitch addTarget:self
                action:@selector(switchDisplayAnchors:)
                forControlEvents:UIControlEventValueChanged];
    }
}

if (anchorsLineWidthSlider == nil) {    
    // Line Width
    if (indexPath.section == 1 && indexPath.row == 0) {
        NSLog(@"Creating anchorsLineWidthSlider");
        self.anchorsLineWidthSlider = [[[UISlider alloc]
                initWithFrame:CGRectMake(0.0, 0.0, 200.0, 0.0)]autorelease];
        self.anchorsLineWidthSlider.continuous = YES;
        self.anchorsLineWidthSlider.value = 0.25;
        cell.accessoryView = self.anchorsLineWidthSlider;

        [self.anchorsLineWidthSlider addTarget:self
                action:@selector(sliderAnchorsLineWidth:)
                forControlEvents:UIControlEventValueChanged];
    }
}

// Line Opacity
if (indexPath.section == 1 && indexPath.row == 1) {
    if (anchorsLineOpacitySlider == nil) {
        NSLog(@"Creating anchorsLineOpacitySlider");
        self.anchorsLineOpacitySlider = [[[UISlider alloc]
                                          initWithFrame:CGRectMake(0.0, 0.0, 200.0, 0.0)]autorelease];
        self.anchorsLineOpacitySlider.continuous = YES;
        self.anchorsLineOpacitySlider.value =0.75;
        cell.accessoryView = self.anchorsLineOpacitySlider;

        [self.anchorsLineOpacitySlider addTarget:self
                                          action:@selector(sliderAnchorsLineOpacity:)
                                forControlEvents:UIControlEventValueChanged];           
        cell.accessoryType = UITableViewCellAccessoryNone;

    }

}

if (indexPath.section == 1 && indexPath.row == 2) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

if (indexPath.section == 1 && indexPath.row == 3) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

if (anchorsFillSwitch == nil) {
    // Display Fill
    if (indexPath.section == 2 && indexPath.row == 0) {
        NSLog(@"Creating anchorsFillSwitch");
        self.anchorsFillSwitch = [[[UISwitch alloc]
                initWithFrame:CGRectZero]autorelease];
        self.anchorsFillSwitch.on = YES;
        cell.accessoryView = self.anchorsFillSwitch;    

        [self.anchorsFillSwitch addTarget:self
                action:@selector(switchAnchorsFill:)
                forControlEvents:UIControlEventValueChanged];
    }
}

if (indexPath.section == 2 && indexPath.row == 1) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

if (indexPath.section == 2 && indexPath.row == 2) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

return cell;

}

Ответы [ 2 ]

1 голос
/ 13 мая 2011

Прежде всего, TableView использует многократно используемые ячейки (как в вашем случае, вы также можете использовать новые ячейки, но это не очень хорошая практика.) Это означает, что если у вас есть ячейка с текстом, написанным как «привет», и она готовадля многоразового использования, то текст остается до тех пор, пока вы не очистите это сообщение перед повторным использованием .. так что в вашем коде перед повторным использованием любой новой ячейки просто очистите ее accessoryType.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
 cell.accessoryType = UITableViewCellAccessoryNone;
//then process your code....before reusing any cell just clear all it components.
0 голосов
/ 13 мая 2011

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

Существует также проблема с тем, как вы устанавливаете вспомогательный вид для раздела 0. После инициализации displayAnchorsSwitch код больше не будет вызываться. Таким образом, только одна строка в разделе 0 будет иметь переключатель, а остальные не будут (на основе кода). Он не будет вызываться, если тот же ряд (один с переключателем) выходит за пределы экрана и снова включается после повторного использования ячейки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...