单行选择 - UITableView

时间:2011-09-23 18:57:19

标签: objective-c ios uitableview

下午好,

我试图在UITableView中选择单行来部署我的应用程序,但是当我选择另一行时,前一行不清楚。我使用图像来表示线条的选择。我试图让每个用户的选择表行保留取消选择的图像,但没有成功。

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

    static NSString *EditCellIdentifier = @"EditCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:EditCellIdentifier];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:EditCellIdentifier] autorelease];

        UILabel *label = [[UILabel alloc] initWithFrame:kLabelRect];
        label.tag = kCellLabelTag;
        [cell.contentView addSubview:label];
        [label release];

        UIImageView *imageView = [[UIImageView alloc] initWithImage:unselectedImage];
        imageView.frame = CGRectMake(5.0, 10.0, 23.0, 23.0);
        [cell.contentView addSubview:imageView];
        imageView.hidden = !inPseudoEditMode;
        imageView.tag = kCellImageViewTag;
        [imageView release];
    }

    [UIView beginAnimations:@"cell shift" context:nil];

    UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kCellImageViewTag];
    NSNumber *selected = [selectedArray objectAtIndex:[indexPath row]];
    imageView.image = ([selected boolValue]) ? selectedImage : unselectedImage;
    imageView.hidden = !inPseudoEditMode;
    [UIView commitAnimations];

    UILabel *label = (UILabel *)[cell.contentView viewWithTag:kCellLabelTag];
    label.text =[listOfItems objectAtIndex:[indexPath row]];
    label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
    label.opaque = NO;

    return cell;
}

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

[tv deselectRowAtIndexPath:indexPath animated:YES];

    if (inPseudoEditMode) {

        BOOL selected = [[selectedArray objectAtIndex:[indexPath row]] boolValue];
        [selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:!selected]];
        [tv reloadData];
    }
}

2 个答案:

答案 0 :(得分:4)

我想你一次只能选择一行。

以下是我在tableView: didSelectRowAtIndexPath:中建议的内容:

将所有行标记为未选中:

for (int i = 0; i < [selectedArray count]; i++) {
    [selectedArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}

然后,将当前行标记为已选:

[selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:YES]];

或者,在for循环中完成所有操作:

for (int i = 0; i < [selectedArray count]; i++) {
    NSNumber rowSelected = [NSNumber numberWithBool:(indexPath.row == i)];
    [selectedArray replaceObjectAtIndex:i withObject:rowSelected];
}

希望这就是你想要的!

答案 1 :(得分:1)

我使用的最短路


for (int i = 0; i < [selectedArray count]; i++) {
    [selectedArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:i==indexpath.row?YES:NO]];
}