Objective c updateSwitchAtIndexPath崩溃
在某些单元格中,我可以看到UISwitch的UITableView 我想捕获事件,但当我尝试添加indexath时,它崩溃了Objective c updateSwitchAtIndexPath崩溃,objective-c,uitableview,uiswitch,Objective C,Uitableview,Uiswitch,在某些单元格中,我可以看到UISwitch的UITableView 我想捕获事件,但当我尝试添加indexath时,它崩溃了 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //Create cell with all data UISwitch *switchview = [[UISwitch alloc] initWi
- (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
谢谢
[switchview addTarget:self action:@selector(updateSwitchAtIndexPath) forControlEvents:UIControlEventTouchUpInside];
应该是
[switchview addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventTouchUpInside];
你只缺了一个冒号。因为你的方法有参数
- (void)updateSwitchAtIndexPath:(NSIndexPath *)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:(UISwitch *)switchview {
if ([switchView isOn]) {
NSLog(@"ON");
} else {
NSLog(@"OFF");
}
}
在上面的代码中,sender表示UISwitch,如果您想要单元格的indexPath,那么标记的行将对您有所帮助。我以前已经尝试过这个方法,但它不起作用:-[UISwitch row]:无法识别的选择器发送到实例0x797c400,可能是因为它是分组UITable吗?请确保您声明了此
-(void)updateSwitchAtIndexPath:(NSIndexPath*)头(.h)中的indexPath
它是声明的,我在问ç抱歉我不明白你的意思之前也检查了这个,没有可见的@interface for'ParkingData'声明选择器'addTarget:action:forControlEvents:'是的!可以!但是,如果我没有indexPath,我怎么知道单击的是哪一行?@user1256477你可以设置你的标签
- (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");
}