Определение первого и последнего UITableViewCell - PullRequest
2 голосов
/ 30 марта 2012

У меня есть UITableView с 3 разделами, каждый из которых возвращает числоOfRows счет в 3 отдельных массивах.В моем cellForRow я должен быть в состоянии определить, какая ячейка является первой ячейкой в ​​таблице, а какая последней.

Хитрость заключается в том, что иногда раздел может возвращать счетчик 0 для количества строк, поэтому мне трудно разобраться с этим.Все, что я пытаюсь сделать, это установить два флага: isTopCell и isBottomCell.Есть идеи?

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0)
        return [array1 count];
    else if(section==1)
        return [array2 count];
    else return [array3 count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 if(/*something, what I'm trying to figure out*/)
      isTopCell=YES;
 if(/*something, what I'm trying to figure out*/)
      isBottomCell=YES;
}

Редактировать: Позвольте уточнить.3 раздела унифицированы.Я хочу определить верхнюю и нижнюю ячейки.if (indexPath.row == 0) вернет true для 3 разделов.Мне нужен только 1 победитель.

Ответы [ 8 ]

2 голосов
/ 30 марта 2012

Попробуйте это:

int index = indexPath.row;
if (indexPath.section > 0) index += [array1 count];
if (indexPath.section > 1) index += [array2 count];

if (index == 0) // Top row

if (index == [array1 count] + [array2 count] + [array3 count] - 1) // Bottom row
1 голос
/ 30 марта 2012

Хитрость не в том, чтобы полагаться на ваш cellForRowAtIndexPath, поскольку он работает только для ячеек, которые видны на экране. Я бы посоветовал выяснить вещи в вашем numberOfSectionsInTableView. Вот код, который должен работать. Сначала давайте добавим два пути индекса к вашему .h файлу:

@interface MyTable : UITableViewController {
    ...
    NSIndexPath *ip_top;
    NSIndexPath *ip_bottom;
}

@property (nonatomic, retain) NSIndexPath *ip_top;
@property (nonatomic, retain) NSIndexPath *ip_bottom;

А в вашем .m файле:

...
@implementation MyTable

@synthesize ip_top;
@synthesize ip_bottom;

и, конечно, нам нужно выпустить их в dealloc:

- (void)dealloc {
    [ip_top release];
    [ip_bottom release];
}

Теперь давайте возьмем мясо и кости логики. Сначала мы изменим numberOfSectionsInTableView, так как он запускается один раз при каждой загрузке / перезагрузке таблицы:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tv {
    NSLog(@"Getting number of sections");
    self.ip_top = self.ip_bottom = nil;
    int i_numSections = 3;
    int i_numRows;
    for (int i=0; i<i_numSections; i++) {
        i_numRows = [self tableView:tv numberOfRowsInSection:i];
        NSLog(@"num_rows:%d for section:%d",i_numRows,i);
        if (i_numRows > 0) {
            if (!ip_top) {
                self.ip_top = [NSIndexPath indexPathForRow:0 inSection:i];
            }
            self.ip_bottom = [NSIndexPath indexPathForRow:i_numRows-1 inSection:i];
        }
    }
    NSLog(@"top:%@ bottom:%@",ip_top,ip_bottom);

    return i_numSections;
}

Обратите внимание, что он найдет первый раздел, содержащий более 1 строки, и укажите ip_top, в противном случае ip_top будет nil. Аналогичная логика для ip_bottom, которая будет указывать на последний ряд. Теперь нам нужно проверить это в нашем cellForRowAtIndexPath:

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

    ...

    if ([indexPath compare:ip_top] == NSOrderedSame) {
        NSLog(@"top cell section:%d row:%d",indexPath.section,indexPath.row);
    }
    if ([indexPath compare:ip_bottom] == NSOrderedSame) {
        NSLog(@"bottom cell section:%d row:%d",indexPath.section,indexPath.row);
    }

    ...
}

Имеет смысл? Иди, возьми их!

1 голос
/ 30 марта 2012
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    BOOl isTopCell = NO;
    BOOl isBottomCell = NO;

    int totalNumberOfCells = [array1 count] + [array2 count] + [array3 count];

    int cellOverallPosition = 0;

    switch (indexPath.section) {
        case 0: { cellOverallPosition = indexPath.row; } break;
        case 1: { cellOverallPosition = indexPath.row + [array1 count]; } break;
        case 2: { cellOverallPosition = indexPath.row + [array1 count] + [array2 count]; } break;
    }

    if (cellOverallPosition == 1) { isTopCell = YES; }

    if (cellOverallPosition == totalNumberOfCells) { isBottomCell = YES; }

    //Other cell stuff follows

}
1 голос
/ 30 марта 2012

Ничего хитрого в этом нет.Вот оно для произвольного числа разделов:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger totalIndex = indexPath.row;
    NSInteger numberOfSections = [self numberOfSectionsInTableView:tableView];
    NSInteger totalNumberOfRows = 0;

    for (NSInteger currentSection = 0; currentSection < numberOfSections; currentSection ++) {
        NSInteger rowsInSection = [self tableView:tableView numberOfRowsInSection:currentSection];
        totalNumberOfRows += rowsInSection;
        if (currentSection < indexPath.section) totalIndex += rowsInSection;
    }

    BOOL isTopCell = (totalIndex == 0);
    BOOL isBottomCell = (totalIndex == totalNumberOfRows);
}
0 голосов
/ 30 марта 2012

Я предполагаю, что вы хотите только верх и низ для всей таблицы, а не для каждого раздела.Первое, что приходит на ум, - это создать массив, который является объединенным содержимым массивов array1, array2 и array3.Затем, когда вы делаете обычную конфигурацию ячейки в cellForRowAtIndexPath:, сравните элемент, который вы извлекаете, используя section и row, с первым и последним элементами вашего накопительного массива.

0 голосов
/ 30 марта 2012

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

я использую следующий код

//
    // Set the background and selected background images for the text.
    // Since we will round the corners at the top and bottom of sections, we
    // need to conditionally choose the images based on the row index and the
    // number of rows in the section.
    //
    UIImage *rowBackground;
    UIImage *selectionBackground;
    NSInteger sectionRows = [aTableView numberOfRowsInSection:[indexPath section]];
    NSInteger row = [indexPath row];
    if (row == 0 && row == sectionRows - 1)
    {
        rowBackground = [UIImage imageNamed:@"topAndBottomRow.png"];
        selectionBackground = [UIImage imageNamed:@"topAndBottomRowSelected.png"];
    }
    else if (row == 0)
    {
        rowBackground = [UIImage imageNamed:@"topRow.png"];
        selectionBackground = [UIImage imageNamed:@"topRowSelected.png"];
    }
    else if (row == sectionRows - 1)
    {
        rowBackground = [UIImage imageNamed:@"bottomRow.png"];
        selectionBackground = [UIImage imageNamed:@"bottomRowSelected.png"];
    }
    else
    {
        rowBackground = [UIImage imageNamed:@"middleRow.png"];
        selectionBackground = [UIImage imageNamed:@"middleRowSelected.png"];
    }
    ((UIImageView *)cell.backgroundView).image = rowBackground;
    ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;

    //


#endif

Дайте мне знать, если это сработало Ура !!!! * * 1006

0 голосов
/ 30 марта 2012

Это должно работать для любого табличного представления - произвольное количество разделов и произвольное количество строк в каждом разделе.Он также обрабатывает случай наличия только одного ряда (определяя ряд как верхний и нижний ряд).Просто добавьте его в начало вашего cellForRowAtIndexPath метода.

BOOL isTop = NO;
BOOL isBottom = NO;
int sections = [self numberOfSectionsInTableView:tableView];
if (indexPath.row == 0) {
  // Could be first
  isTop = YES;
  for (int i = indexPath.section-1; i>=0; i--) {
    if ([self tableView:tableView numberOfRowsInSection:i] > 0) {
      // Non-empty section above this one, so not first.
      isTop = NO;
      break;
    }
  }
}
if (indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section]-1) {
  // Could be last
  isBottom = YES;
  for (int i = indexPath.section + 1; i < sections; i++) {
    if ([self tableView:tableView numberOfRowsInSection:i] > 0) {
      // Non-empty section below this one, so not last.
      isBottom = NO;
      break;
    }
  }
}
0 голосов
/ 30 марта 2012

для первого

if(indexPath.row == 0)

за последние

if(indexPath.row == sectionarray.count - 1)

и с sectionarray я имею в виду, конечно, ваши массивы 1-3 вам придется определить, какой использовать с

indexPath.section

, который вернет значения 0,1,2 для вас 3 раздела =)

в качестве альтернативы вы можете получить такой счет

[self tableView:tableView numberOfRowsInSection:indexPath.section]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...