代码之家  ›  专栏  ›  技术社区  ›  user1256477

updateSwitchAtIndexPath崩溃

  •  0
  • user1256477  · 技术社区  · 12 年前

    我在一些单元格中有一个UITableView和UISwitch。

    我想捕捉事件,但当我尝试添加indexPath时,它会崩溃。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
     //Create cell with all data
    
        UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
        cell.accessoryView = switchview;
        [switchview addTarget:self action:@selector(updateSwitchAtIndexPath) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    - (void)updateSwitchAtIndexPath:(NSIndexPath *)indexPath {
    
       UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
       UISwitch *switchView = (UISwitch *)cell.accessoryView;
    
       if ([switchView isOn]) {
           NSLog(@"ON");
       } else {
           NSLog(@"OFF");
       }
    
    }
    

    它崩溃了,我想是因为我没有添加indexPath参数,但我不知道如何设置它。

     -[ParkingData updateSwitchAtIndexPath]: unrecognized selector sent to instance 0x7b88eb0
    

    谢谢

    3 回复  |  直到 12 年前
        1
  •  1
  •   Mil0R3    12 年前

    更新

     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    
     //Create cell with all data
    
        UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
        cell.accessoryView = switchview;
        [switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    - (void)updateSwitchAtIndexPath:(UISwitch *)switchview {
       if ([switchView isOn]) {
           NSLog(@"ON");
       } else {
           NSLog(@"OFF");
       }
    
    }
    
        2
  •  1
  •   janusfidel    12 年前
    [switchview addTarget:self action:@selector(updateSwitchAtIndexPath) forControlEvents:UIControlEventTouchUpInside];
    

    应该是

    [switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventTouchUpInside];
    

    你只缺了一个冒号。因为你的方法有参数。

    - (void)updateSwitchAtIndexPath:(NSIndexPath *)indexPath
    
        3
  •  0
  •   quetzalcoatl    12 年前
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
        cell.accessoryView = switchview;
        [switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    - (void)updateSwitchAtIndexPath:(id)sender
    {
       // see the line BELOW
       NSIndexPath *indexPath = [[(UITableView*)[sender superview] superview]indexPathForCell: (UITableViewCell*)[sender superview]];
    
        if ([sender isOn])
            NSLog(@"ON");
        else
            NSLog(@"OFF");
    }
    

    在上面的代码发送器意味着UISwitch,如果你想要单元格的indexPath,那么标记的行对你有帮助。

    推荐文章