我已经尝试了这里发布的几种方法,但我无法让我的表充满开关以返回已更改开关的单元格的索引值。我正在以编程方式创建包含表的 View (无 xib)。
TableSandboxAppDelegate.m 我在 didFinishLaunchingWithOptions:
中实例化 View Controller :
...
TableSandboxViewController *sandboxViewController = [[TableSandboxViewController alloc]
init];
[[self window] setRootViewController:sandboxViewController];
...
TableViewController.h 文件内容如下:
@interface TableSandboxViewController : UITableViewController
{
NSMutableArray *_questionOrder;
NSMutableArray *switchStates;
}
@end
TableViewController.m cellForRowAtIndexPath:
读取:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
UISwitch *theSwitch = nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"MainCell"];
theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
theSwitch.tag = 100;
[theSwitch addTarget:self action:@selector(switchChanged:)
forControlEvents:UIControlEventValueChanged];
[cell.contentView addSubview:theSwitch];
} else {
theSwitch = [cell.contentView viewWithTag:100];
}
if ([[switchStates objectAtIndex:indexPath.row] isEqualToString:@"ON"]) {
theSwitch.on = YES;
} else {
theSwitch.on = NO;
}
return cell;
TableViewController.m -(IBAction)switchChanged:(UISwitch *)sender
读取:
UITableViewCell *theParentCell = [[sender superview] superview];
NSIndexPath *indexPathOfSwitch = [self.tableView indexPathForCell:theParentCell];
NSLog(@"Switch changed at index: %d", indexPathOfSwitch.row);
我的日志结果总是“Switch changed at index: 0”。我觉得问题出在 CGPoint 行中,我在其中尝试了“发件人”的替换组合([sender superview]、[[sender superview]superview] 等)。我不觉得那条线指向显示表格的 View 。
我做错了什么?
注意在美国东部时间 10 月 9 日 9:15 添加:我的目标是能够处理表中大约 100 个是/否问题,因此重用是关键。我想滚动并让表格显示每个开关的状态,并能够在离开 View 时检索它们。
最佳答案
标签是一个不错的解决方案,但有点笨拙,因为单元格 - 以及它们的 subview - 不断被重用,改变它们的行 - 因此它们需要标签。
相反,我通常会保留其中之一:
- (NSIndexPath *)indexPathWithSubview:(UIView *)subview {
while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
subview = subview.superview;
}
return [self.tableView indexPathForCell:(UITableViewCell *)subview];
}
然后当我得到一个 IBAction 时:
- (IBAction)someSubviewAction:(id)sender {
NSIndexPath *indexPath = [self indexPathWithSubview:(UIView *)sender];
// carry on from here
}
关于iphone - 如何检索 UISwitch 的 UITableView 行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19262361/