首页 文章

如何使用tag属性在自定义单元格的表视图中检查多个UISwitch控件的状态

提问于
浏览
1

我有一个自定义UITableViewCell的tableview . Cell有 UISwitch 控件 . 我已将单元格添加到表视图控制器中,并为所有开关执行相同的操作 . 我在 cellForRowAtIndexPath 方法中添加了 UISwitch 的标记值 .

当用户更改开关状态时,我想确定更改了什么开关 . 这里我在 UISwitch 按钮上设置动作 .

- (void)viewDidLoad
{
    [super viewDidLoad];
    cell.switchbtn.userInteractionEnabled=YES;
    [cell.switchbtn setOn:YES];
    [cell.switchbtn addTarget:self action:@selector(switchToggled:) forControlEvents:   UIControlEventValueChanged];
    [cell.contentView addSubview:cell.switchbtn];
}

我在这里设置uiswitch的标签值

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellidentifier=@"cellid";
    cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];

    if (!cell)
    {
        [[NSBundle mainBundle] loadNibNamed:@"cellid" owner:self options:nil];

    }

    cell.switchbtn.tag=indexPath.row;
    NSLog(@"btn tag=%d",cell.switchbtn.tag);
    return cell;
}

这里我调用switchToggled:方法来获取uiswitch状态 .

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
  [self switchToggled:cell.switchbtn];
}

我正在获取标记值,每次状态为On . 即使状态为关闭 .

- (void) switchToggled:(UISwitch *)sender {
    UISwitch *mySwitch = (UISwitch *)sender;

    NSLog(@"tag ==%@",mySwitch);
    if ([mySwitch isOn]) {
        NSLog(@"its on!");
    } else {
        NSLog(@"its off!");
    }
}

2 回答

  • 0

    使用具有直接Cell属性的CGpoint来识别选择哪一行,并且该单元的Uiswitch状态可以更容易地识别,这是我正在使用的一种方法,它对我来说工作正常 .

    - (void)switchToggled:(id)sender
    {
    
        CGPoint switchPositionPoint = [sender convertPoint:CGPointZero toView:[self tableName]];
        NSIndexPath *indexPath = [[self tableName] indexPathForRowAtPoint:switchPositionPoint];
    
        BusinessHoursCell *cell = (BusinessHoursCell*)[self.tableName cellForRowAtIndexPath:indexPath];
    
        int tag=indexPath.row;
    
        if (tag==0)
        {
            if (cell.workingDaySwitch.on)
            {
                NSLog(@"its on!");
            }
    
            else
            {
                NSLog(@"its off!");
            }
        }
    }
    
  • 1

    我将使用以下方案:在cellForRowAtIndexPath中:..将当前indexPath设置为cell . 使用 - (void)cellAtIndexPath:(NSIndexPath *)path changedSwitchStateToState:(BOOL)state 等方法创建协议,为单元格创建控制器委托 . Cell通过调用该委托方法来处理切换状态更改 .

    在控制器中,你应该为dataSource(可能是自定义类)使用一些东西,它存储用于配置单元格的对象,并且有一个类似于 - (void)changeSwitchStateToState:(BOOL)state atIndexPath:(NSIndexPath *)path 的方法,它获取相应的对象并更新状态 .

相关问题