в некоторых случаях галочка на uitableviewcell не отображается - PullRequest
3 голосов
/ 14 октября 2011

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

В таблице около 100-200 записей, и у меня есть дополнительное представление, котороеэто отметка, что, когда ячейка выбрана, она помечает ячейку, а затем снова загружает основной вид.

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

Она имеет тенденцию работать примерно в верхних 30/40% таблицы, ночто-нибудь ниже, тик не будет виден ... то есть, если я не буду все больше и больше становиться все глубже и глубже, то иногда я могу заставить тик появляться в более глубокой части табличного представления ... Кто-нибудь знает, почему это происходит??

Кто-нибудь имел что-то подобное с ними раньше?

При дальнейшем исследовании я думаю, что-нибудьВ этом методе происходит сбой ng.

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

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

 // Navigation logic may go here. Create and push another view controller.
    [self.navigationController popViewControllerAnimated:YES]; //pops current view from the navigatoin stack

    //accesses selected cells content
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // now you can use cell.textLabel.text

    //This if statment is based off which cell was selected in the parent view so that it knows which cell to pass the data back to
    if (parentViewSelectedIndexPath.section == 0) {
        if (parentViewSelectedIndexPath.row == 0) {
            manufactureCellTextLabel = cell.textLabel.text; //passing label text over to NSString for use with delegate (check "viewwilldissapear")
            [[self delegate] setManufactureSearchFields:manufactureCellTextLabel withIndexPath:indexPath]; //This is where I pass the value back to the mainview
        }
// a few more If statements for the other methods I can pass data too.


//--- this if block allows only one cell selection at a time
    if (oldCheckedData == nil) { // No selection made yet
        oldCheckedData = indexPath;
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];

    }
    else {
        UITableViewCell *formerSelectedcell = [tableView cellForRowAtIndexPath:oldCheckedData]; // finding the already selected cell
        [formerSelectedcell setAccessoryType:UITableViewCellAccessoryNone];

        [cell setAccessoryType:UITableViewCellAccessoryCheckmark]; // 'select' the new cell
        oldCheckedData = indexPath;
    }   
}

. Это передает путь индекса в основное представление.метод ...

   - (void) setManufactureSearchFields:(NSString *)cellLabeltext withIndexPath:(NSIndexPath *)myIndexPath
    {
        manufactureSearchObjectString = cellLabeltext;
        manufactureResultIndexPath = myIndexPath;
        [self.tableView reloadData]; //reloads the tabels so you can see the value.
    }

//, который затем устанавливает factoryResultIndexPath, который используется в следующем методе, чтобы передать его обратно в подпредставление

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    //--- Idendify selected indexPath (section/row)
    if (indexPath.section == 0) {
        //--- Get the subview ready for use
        VehicleResultViewController *vehicleResultViewController = [[VehicleResultViewController alloc] initWithNibName:@"VehicleResultViewController" bundle:nil];
        // ...
        //--- Sets the back button for the new view that loads
        self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:nil action:nil] autorelease];

        // Pass the selected object to the new view controller.
        [self.navigationController pushViewController:vehicleResultViewController animated:YES];

        [vehicleResultViewController setDelegate:self];

        if (indexPath.row == 0) 
        {
            vehicleResultViewController.title = @"Manufacture";
            [vehicleResultViewController setRequestString:@"ID.xml"]; //sets the request string in searchResultsViewController
            vehicleResultViewController.dataSetToParse = @"ID"; // This is used to controll what data is shown on subview... logic
            [vehicleResultViewController setAccessoryIndexPath:manufactureResultIndexPath]; //sends indexpath back to subview for accessory tick
            vehicleResultViewController.parentViewSelectedIndexPath = indexPath;
        }


//etc etc
}

И наконец я передаю егометод в моем подпредставлении, который передает indexpath к oldCheckedData

- (void)setAccessoryIndexPath:(NSIndexPath *)myLastIndexPath
{
                oldCheckedData = myLastIndexPath;
                [self.tableView reloadData]; //<<---- this is where I reload the table to show the tick...
}

Ответы [ 2 ]

2 голосов
/ 14 октября 2011

Попробуйте переместить строки cell.accessoryType = в функцию делегата willDisplayCell: следующим образом:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    // You can move this one here too:
    cell.selectionStyle = UITableViewCellSelectionStyleNone; // no blue selection

    if (indexPath == oldCheckedData) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    } 
}

Я прочитал, что метод willDisplayCell: должен использоваться для любых базовых визуальных модификаций в ячейке, таких как selectionStyle / accessoryType, и метод cellForRowAtIndexPath: для операций, связанных с данными ячейки, таких как настройка текста, изображений и т. Д. ...

0 голосов
/ 04 мая 2019

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

 public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

..logic here to to determine if cell should be selected...

if ( cell.accessoryView != nil) {
    cell.accessoryView?.removeFromSuperview()
    cell.accessoryView = nil
}
cell.accessoryType = .checkmark
...