UITableViewCellAccessory исчезает при прокрутке выключенного экрана - PullRequest
2 голосов
/ 29 апреля 2011

У меня UITableView заполнен объектами.В методе didSelectRowAtIndexPath у меня появляется метка UITableViewCellAccessoryCheck, когда строка выбрана, и исчезает, когда она не выбрана.

Вот код для метода didSelectRowAtIndexPath :

1008*

У меня также есть это как мой cellForIndexPath :

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


static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];

    for (id currentObject in topLevelObjects){
        if ([currentObject isKindOfClass:[UITableViewCell class]]){
            cell =  (CustomCell *) currentObject;
            break;
        }
    }
}

// Setting separate tables correctly....


return cell;
}

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

Что я должен сделать, чтобы не пропустить флажок?

Спасибо

Ответы [ 5 ]

4 голосов
/ 29 апреля 2011

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

Вам необходимо установить / отменить вспомогательное представление в cellForRowAtIndexPath, чтобы проверенные строки прокручивались обратновид, они проверены соответствующим образом.

1 голос
/ 05 января 2014

для тех, кто хочет более общего подхода и для нескольких выбранных ячеек

Сначала создайте (NSMutableArray *) selectedCells, чтобы отслеживать выбранные ячейки. Далее реализуем 2 метода делегата

-(void)tableView:(UITableView *)tableView 
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

//add the checkmark to cell when selected
if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryNone){
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;

}

//once selected add that selected cell to the selectedCells array 

[self.selectedCells addObject:@(indexPath.row) ];

}

И

-(void)tableView:(UITableView *)tableView 
                 didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{ 

//set the accessory type back to none 
if([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark){
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
}

//remove the selected cells index from the selectedCells array
[self.selectedCells removeObject:@(indexPath.row) ];

}

Теперь, когда вы выбираете ячейку, добавляется галочка, и этот indexPath.row сохраняется в NSMutableArray. Когда вы отменяете выбор этой ячейки, она удаляет галочку и удаляет ее из массива. Это означает, что массив будет содержать только проверенные ячейки.

Затем мы используем этот массив, чтобы дать ячейке правильный accessoryType в методе cellForRowAtIndexPath. Этот метод вызывается каждый раз, когда tableView требует ячейку, мы говорим, что для продажи требуется наличие checkMark при создании или нет.

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

 static NSString *CellIdentifier = @"Cell";
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
  cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

//Create an NSNumber to hold the row of the cell to be created   
   NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.row];

//then ask the array if the selectedCells array has that object.
//if it does then that cell needs a checkmark when created.

if ([self.selectedCells containsObject:rowNsNum]){
   cell.accessoryType = UITableViewCellAccessoryCheckmark;
     }
else { cell.accessoryType = UITableViewCellAccessoryNone;
     }

    [cell.textLabel setText:@"your contents"];
 }

 return cell;
 }
0 голосов
/ 09 июля 2012

Это то, что я считаю наиболее подходящим:

(просто любой код между «Добавить это» и «Конец добавить это»)

Также убедитесь, что вы изменили "(Ваш номерofRows) "к объекту, который либо возвращает int, либо сам является int.Например, myCustomArray.count или 24.

//In .h file add this
NSMutableArray *indexArray;

//in .m file 

- (void)viewDidLoad {
    //Add this
    indexArray = [[NSMutableArray alloc] init];
    int i;
    for (i = 0; i <= (Your Number ofRows); i++) {
        [indexArray addObject:[NSNumber numberWithDouble:0]];
    }
NSLog(@"indexArray = %@",indexArray);//You can check the console now to see if you have an array of "zeros" 
    //End Add this
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
UITableViewCell *curCell = [beerTable cellForRowAtIndexPath:indexPath];


if (curCell.accessoryType == UITableViewCellAccessoryCheckmark) {
    [curCell setAccessoryType:UITableViewCellAccessoryNone];
    compareCount = (compareCount - 1);

    //Add this
    [indexArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithDouble:0]]; 
    //End Add this


    if (tableView == [[self searchDisplayController] searchResultsTableView]) {
        NSString *objBeer = [searchResults objectAtIndex:indexPath.row];
        [compareBeers removeObject:[searchResults objectAtIndex:indexPath.row]];
        [compareCarbs removeObject:[carbAmount objectAtIndex:[beerNames indexOfObject:objBeer]]];
    }
    else {
        [compareBeers removeObject:[beerNames objectAtIndex:indexPath.row]];
        [compareCarbs removeObject:[carbAmount objectAtIndex:indexPath.row]];
    }

}
else {
    [curCell setAccessoryType:UITableViewCellAccessoryCheckmark];
    compareCount = (compareCount + 1);

    //Add this
    [indexArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithDouble:1]]; 
    //End Add this

    if (tableView == [[self searchDisplayController] searchResultsTableView]) {
        NSString *objBeer = [searchResults objectAtIndex:indexPath.row];
        [compareBeers addObject:[searchResults objectAtIndex:indexPath.row]];
        [compareCarbs addObject:[carbAmount objectAtIndex:[beerNames indexOfObject:objBeer]]];
    }
    else {
        [compareBeers addObject:[beerNames objectAtIndex:indexPath.row]];
        [compareCarbs addObject:[carbAmount objectAtIndex:indexPath.row]];
    }

}

if (compareCount > 0) {
    if (compareOn == YES){
    }
    else {
        compareButton.enabled = YES;
        UIImage *image = [UIImage imageNamed:@"redbutton.png"];
        [compareButton setImage:image];
    }
}

else {
    compareButton.enabled = NO;
    [compareButton setImage:nil];
    [compareButton setCustomView:nil];
}

}    



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


static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];

    for (id currentObject in topLevelObjects){
        if ([currentObject isKindOfClass:[UITableViewCell class]]){
            cell =  (CustomCell *) currentObject;
            break;
        }
    }
}

// Setting separate tables correctly....

//Add this
if ([[indexArray objectAtIndex:indexPath.row] doubleValue] == 1) {
    cell.accesoryType = UITableViewCellAccesoryTypeCheckmark;
} else {
    cell.accesoryType = UITableViewCellAccesoryTypeNone; 
}
//End Add this 

return cell;
}
0 голосов
/ 29 апреля 2011

Попробуйте сохранить выбранный индекс в массиве или словаре для выбранной ячейки в методе didSelectRow, а в cellForRowAtIndexPath проверьте, доступен ли этот индекс в массиве, затем отметьте ячейку с помощью параметра accesoryType. Надеюсь, вы понимаете

0 голосов
/ 29 апреля 2011

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

Вам необходимо каждый раз сбрасывать статус ячейки в cellForRowAtIndexPath. Ваш код имеет эту область комментариев // Правильная установка отдельных таблиц ....

Здесь вы делаете настройку. Когда это вызывается, проверьте, должна ли ячейка отображать галочку, и установите ее соответственно

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