开发者

TableView returns null (0) when selecting row

I have a TableView control which I've sectioned/grouped. However this has now broken the code which determines the item I've selected in the Table.

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

    /*
     When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
     */
    //detailViewController.detailItem = [NSString stringWithFormat:@"Row %d", indexPath.row];
    if (_delegate != nil) {
        Condition *condition = (Condition *) [_conditions objectAtIndex:indexPath.row];
        [_delegate conditionSelectionChanged:condition];
    }
}

My开发者_如何学运维 sample data currently has 6 sections, the first one contains two items with all the rest containing one. If I select the second item in the first section, the details view updates fine, any other selection always shows the first item in the first section (item 0).

I'm assuming this is because indexPath.row is returning 0 for the other sections as it's the first item in that section, which is then causing the first object from my array to be chosen.

How do I fix my code to ensure the correct item is selected? Everything else works fine other than this.

cellForRowAtIndexPath

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

    static NSString *CellIdentifier = @"CellIdentifier";

    // Dequeue or create a cell of the appropriate type.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    //get the letter in the current section
    NSString *alphabet = [conditionIndex objectAtIndex:[indexPath section]];

    //get all conditions beginning with the letter
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name beginswith[c] %@", alphabet];
    NSArray *conditionsGrouped = [_conditions filteredArrayUsingPredicate:predicate];

    if ([conditionsGrouped count] > 0) {
        Condition *condition = [conditionsGrouped objectAtIndex:indexPath.row];
        cell.textLabel.text = condition.name;
    }

    return cell;
}


You should take into account indexPath.section, as well.

You should create a bi-dimensional _conditions array, indexed by section and then by row.


Got it working by following the answer at this post: UITableView Problem with Sections

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜