Подтвердить что ты не робот

Как получить все ячейки в UITableView

Скажем, у меня есть UITableView, который имеет несколько строк. Я хочу получить все UITableViewCells как NSArray в определенный момент времени. Я пробовал

[tableView visibleCells] 

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

-(NSArray *)cellsForTableView:(UITableView *)tableView
{
    NSInteger sections = tableView.numberOfSections;
    NSMutableArray *cells = [[NSMutableArray alloc]  init];
    for (int section = 0; section < sections; section++) {
        NSInteger rows =  [tableView numberOfRowsInSection:section];
        for (int row = 0; row < rows; row++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];   // **here, for those cells not in current screen, cell is nil**
            [cells addObject:cell];
        }
    }
    return cells;
}

но кажется, что этот подход все еще не может получить те ячейки, которые не отображаются на экране. Может ли кто-нибудь помочь мне в этом?

4b9b3361

Ответ 1

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

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

Ответ 2

Вот простейшее решение в Swift 3.0

func getAllCells() -> [UITableViewCell] {

    var cells = [UITableViewCell]()
    // assuming tableView is your self.tableView defined somewhere
    for i in 0...tableView.numberOfSections-1
    {
        for j in 0...tableView.numberOfRowsInSection(i)-1
        {
            if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) {

               cells.append(cell)
            }

        }
    }
 return cells
 }

Ответ 3

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *Cell = [self dequeueReusableCellWithIdentifier:@"Custom_Cell_Id"];
    if (Cell == NULL)
    {
        Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Custom_Cell_Id"]];
        [Cells_Array addObject:Cell];
    }
}

- (void) DoSomething
{
    for (int i = 0;i < [Cells count];i++)
    {
        CustomCell *Cell = [Cells objectAtIndex:i];
        //Access cell components
    }
}

Ответ 4

Я думаю, что вы можете не понимать, как реализуется UITableView. Важным моментом для понимания является то, что ячейки, которые не видны, фактически не существуют (или, по крайней мере, они не могут)

При прокрутке UITableView старые ячейки заменяются новыми ячейками в силу dequeueReusableCellWithIdentifier  используется в

-(UITableViewCell) cellForRowAtIndexPath (NSIndexPath *)indexPath

Ответ 5

Хотите значения этих текстовых полей? Если да, вы можете получить доступ через свойство тега текстового поля с помощью indexpath.row

Ответ 6

Однако более простая реализация для получения текущих ячеек будет использовать Set i.e O (1)

/// Reference to all cells.
private var allCells = Set<UITableViewCell>()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Your_Cell_ID") as! UITableViewCell
    if !allCells.contains(cell) { allCells.insert(cell) }
    return cell
}

Ответ 7

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

 -(NSMutableArray *)cellsForTableView:(UITableView *)tableView
  {
  NSMutableArray *cells = [[NSMutableArray alloc]  init];

//Need to total each section
for (int i = 0; i < [tableView numberOfSections]; i++) 
{
    NSInteger rows =  [tableView numberOfRowsInSection:i];
    for (int row = 0; row < rows; row++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:i];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        for (UIView *subView in cell.subviews)
        {
            if ([subView isKindOfClass:[UITextField class]]){
                UITextField *txtField = (UITextField *)subView;
                [cells addObject:txtField.text];

            }
        }

    }

}
return cells;

}

-(void) reloadViewHeight
 {
    float currentTotal = 0;

//Need to total each section
for (int i = 0; i < [self.tableView numberOfSections]; i++) 
{
    CGRect sectionRect = [self.tableView rectForSection:i];
    currentTotal += sectionRect.size.height;
}

//Set the contentSizeForViewInPopover
self.contentSizeForViewInPopover = CGSizeMake(self.tableView.frame.size.width, currentTotal);

}