0

我',在某些单元格中有一个带有 UISwitch 的 UITableView。

我想捕获事件,但是当我尝试添加 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

谢谢!

4

3 回答 3

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

应该

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

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

- (void)updateSwitchAtIndexPath:(NSIndexPath *)indexPath
于 2012-08-30T07:41:53.460 回答
1

更新

 - (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");
   }

}
于 2012-08-30T07:47:28.553 回答
0
- (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,那么标记的行对你有帮助。

于 2012-08-30T10:18:55.480 回答