didSelectRowAtIndexPath с разделом - PullRequest
       8

didSelectRowAtIndexPath с разделом

4 голосов
/ 07 февраля 2011

У меня есть UITableView, которому я назначил разделы.При использовании didSelectRowAtIndex с indexPath.row я не получаю правильное значение.Допустим, я нахожусь в разделе 2, затем он снова начинает индекс строки с 0, и поэтому я получаю неправильный индекс.

Может кто-нибудь сказать мне, как это исправить?Я понимаю, что можно получить индекс раздела по indexPath.section, но я не могу понять, как его использовать.

bandDetailViewController.band = [self.programArray objectAtIndex:indexPath.row];

Надеюсь, вы мне поможете.Заранее спасибо: -)

РЕДАКТИРОВАТЬ:

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

<array>
    <dict>
        <key>name</key>
        <string>Alphabeat</string>
        <key>description</key>
        <string>Long description.</string>
        <key>scene</key>
        <string>Store Scene</string>
        <key>date</key>
        <date>2011-02-04T20:09:40Z</date>
        <key>hasDate</key>
        <true/>
        <key>weekDay</key>
        <string>Onsdag</string>
        <key>youtubeVideo</key>
        <string>http://www.youtube.com/watch?v=dB01PTZNpBc</string>
    </dict>
    <dict>
        <key>name</key>
        <string>Anne Linnet</string>
        <key>description</key>
        <string>Long description.</string>
        <key>scene</key>
        <string>Store Scene</string>
        <key>date</key>
        <date>2011-02-04T20:09:40Z</date>
        <key>hasDate</key>
        <true/>
        <key>weekDay</key>
        <string>Onsdag</string>
        <key>youtubeVideo</key>
        <string>http://www.youtube.com/watch?v=jWMSqS7fL9k</string>
    </dict>
</array>

Ответы [ 7 ]

7 голосов
/ 13 июля 2013

Я только что столкнулся с этой проблемой.Я нашел простое решение, используя номер раздела, как вы упомянули. В следующем коде используются переходы для перехода к новому controlView из двух разных разделов с двумя разными строками.ОЧЕНЬ простое решение!

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


if (indexPath.section == 0)
{


    switch(indexPath.row) {
        case 0:
            [self performSegueWithIdentifier:@"Mission" sender:self];
            break;
        case 1:
            //[self performSegueWithIdentifier:@"Music" sender:self];
            break;

     }
}else{

    switch(indexPath.row) {
        case 0:
            [self performSegueWithIdentifier:@"Contact" sender:self];
            break;
        case 1:
            //[self performSegueWithIdentifier:@"Home" sender:self];
            break;
    }


}

}
5 голосов
/ 07 февраля 2011

rows не являются последовательными и начинаются с нуля в каждом section:

секция 0:
строка 0
строка 1
строка 2
строка ...

раздел 1:
строка 0
строка 1
строка 2
строка ...

...

Лучшим способом является создание разделов NSMutableArray с NSMutableArrays для строк. Чем ваш код становится очень простым:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return cellSections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    CellSection *cellSection = [cellSections objectAtIndex:section];
    return cellSection.cellElements.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = [NSString stringWithFormat:@"Cell-%i-%i", indexPath.section, indexPath.row];

    CellSection *cellSection = [cellSections objectAtIndex:indexPath.section];
    CellElement *cellElement = [cellSection.cellElements objectAtIndex:indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];

        [cell.contentView addSubview:cellElement.contentView];

    }


    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CellSection *cellSection = [cellSections objectAtIndex:indexPath.section];
    CellElement *cellElement = [cellSection.cellElements objectAtIndex:indexPath.row];

}

РЕДАКТИРОВАТЬ:

Просто пример:

@interface CellSection : NSObject {

}

@property (nonatomic, retain) NSMutableArray *cellElements;
@property (nonatomic, retain) NSString *headerString;
@property (nonatomic, retain) UIView *headerView;

@end

@interface CellElement : NSObject {

}

@property (nonatomic, retain) UIView *contentView;
@property BOOL isSelectable;
@property BOOL hasAccessoryIndicator;
@property SEL action;

@end
4 голосов
/ 04 июля 2013

У меня была такая же проблема, и я решил ее следующим образом:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *selected = [_products objectAtIndex:[self getRealIndexFromIndexPath:indexPath]];
NSLog(@"%@", selected);

}

- (NSUInteger)getRealIndexFromIndexPath:(NSIndexPath*)indexPath {   
NSUInteger temp = 0;
for (int i = 0; i < indexPath.section ; i++) {
    temp += [_mySectionedTable numberOfRowsInSection:i];
}
return temp + indexPath.row;

}

Надеюсь, это поможет :-) Ура!

1 голос
/ 30 июня 2011

Если вы внедрили

tableview cellForRowAtIndexPath

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

NSString *selectedValue = [self tableView:theTableView cellForRowAtIndexPath:indexPath].textLabel.text;

1 голос
/ 07 февраля 2011

Если я буду следовать за вами правильно, вы можете попробовать

NSUInteger index = indexPath.row * (indexPath.section + 1);
bandDetailViewController.band = [self.programArray objectAtIndex:index];

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

0 голосов
/ 07 февраля 2011

Обычный подход к работе с разделами переменной длины (который, как я полагаю, имеет место в данном случае) заключается в создании коллекции, представляющей разделы, содержащие вложенные коллекции, для представления строк. Так, например, у вас может быть верхний уровень NSMutableArray значений секций, где каждый элемент представляет собой NSMutableArray значений строк.

EDIT

Учитывая текущую структуру ваших plist-данных, другим подходом будет фильтрация массива с использованием экземпляра NSPredicate. Например, следующий код будет фильтровать строки для текущего раздела по дням недели:

static NSArray *days;

if (days == nil)
{
    // Populate the array with days of the week in the order 
    // in which you want the table view to present the sections.
    days = [NSArray arrayWithObjects:@"Monday", @"Tuesday", nil];
}

NSString *day = [days objectAtIndex:[indexPath section]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"weekDay like %@", day];
NSArray *filteredDicts = [[self programArray] filteredArrayUsingPredicate:predicate];

Обратите внимание, что вам также необходимо изменить tableView:numberOfRowsInSection:, чтобы использовать тот же механизм, чтобы он возвращал правильное количество строк для каждого раздела.

0 голосов
/ 07 февраля 2011

Если вы посмотрите документацию NSIndexPath , вы увидите, как устроена структура данных NSIndexPath.

Чтобы получить номер раздела, вы хотите сделать что-то вроде:

[indexPath indexAtPosition:0]

Чтобы получить строку в этом разделе:

[indexPath indexAtPosition:1]
...