如何判断哪些行切换开关已更改

时间:2012-02-24 20:58:34

标签: iphone objective-c nsmutablearray uiswitch

我有一个带有切换开关附件视图的桌面视图。我指定了部分和行,并且很难确定哪一行被切换。我使用toggleSwitch.tag来获取indexRow,但由于我的indexRow是indexPath.section的一部分,我不知道如何判断我切换了哪一行。

以下是代码:

- (UITableViewCell *)tableAlert:(SBTableAlert *)tableAlert cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;

Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];

cell = [[[SBTableAlertCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
UISwitch *toggleSwitch = [[UISwitch alloc] init];
cell.accessoryView = [[UIView alloc] initWithFrame:toggleSwitch.frame];
[cell.accessoryView addSubview:toggleSwitch];

cell.textLabel.text =sub.title;   
cell.detailTextLabel.text = sub.category_title;

if (sub.active==1){
    [toggleSwitch setOn:YES];
} else {
    [toggleSwitch setOn:NO];
}

toggleSwitch.tag = indexPath.row;

[toggleSwitch addTarget:self action:@selector(viewButtonPushed:) forControlEvents:UIControlEventValueChanged];
[toggleSwitch release];

return cell;

}


- (void)viewButtonPushed:(id)sender {
UIButton *button = (UIButton *)sender;    
UITableViewCell *cell = button.superview; // adjust according to your UITableViewCell-subclass' view hierarchy
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];

selectedSubject = sub;

UISwitch* switchControl = sender;
NSLog( @"The switch is %@", switchControl.on ? @"ON" : @"OFF" );

if(switchControl.on){
    [sub setActive:1];
    NSLog(@"%@ is being set to ACTIVE", selectedSubject.title);
}else{
    [sub setActive:0];
    NSLog(@"%@ is being set to INACTIVE", selectedSubject.title);
}

[sub setIsDirty:YES];

[cat.subjects replaceObjectAtIndex:indexPath.row withObject:sub];

[sub autorelease];
[cat autorelease];

}

这是我的didSelectRowAtIndexPath。我需要在这里引用toggleSwitch吗?

- (void)tableAlert:(SBTableAlert *)tableAlert didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];

selectedSubject = sub;
NSLog(@"selectedSubject = %@", selectedSubject.title);


if (tableAlert.type == SBTableAlertTypeMultipleSelct) {
    UITableViewCell *cell = [tableAlert.tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryNone)
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    else
        [cell setAccessoryType:UITableViewCellAccessoryNone];

    [tableAlert.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

}

1 个答案:

答案 0 :(得分:1)

我发现你需要转到单元格中项目的超级视图的超级视图(假设按钮或控件正好在单元格的根目录之外)才能获得指向单元格的指针。 / p>

请改为尝试:

UITableViewCell *cell = button.superview.superview;

并查看结果是否更好。有关更多信息,请查看我的博客文章:

Two superviews are better than one