How can I loop through UITableView's cells?

前端 未结 8 1160
时光说笑
时光说笑 2020-12-07 13:04

I have n sections (known amount) and X rows in each section (unknown amount. Each row has a UITextField. When the user taps the \"Done\" button I want to iterate through eac

8条回答
  •  感情败类
    2020-12-07 13:52

    Since iOS may recycle tableView cells which are off-screen, you have to handle tableView one cell at a time:

    NSIndexPath *indexPath;
    CustomTableViewCell *cell;
    
    NSInteger sectionCount = [tableView numberOfSections];
    for (NSInteger section = 0; section < sectionCount; section++) {
        NSInteger rowCount = [tableView numberOfRowsInSection:section];
        for (NSInteger row = 0; row < rowCount; row++) {
            indexPath = [NSIndexPath indexPathForRow:row inSection:section];
            cell = [tableView cellForRowAtIndexPath:indexPath];
            NSLog(@"Section %@ row %@: %@", @(section), @(row), cell.textField.text);
        }
    }
    

    You can collect an NSArray of all cells beforehands ONLY, when the whole list is visible. In such case, use [tableView visibleCells] to be safe.

提交回复
热议问题