我的 tableView 的每个单元格都有一个 UISwitch 作为 accessoryView:
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = mySwitch;
[mySwitch addTarget:self action:@selector(SwitchToggle:) forControlEvents:UIControlEventValueChanged];
当用户点击它时切换开关,但我也希望它在调用 didSelectRowAtIndexPath 时切换(当用户点击该单元格时)。
我试过了(但没用):
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UISwitch *tempSwitch = (UISwitch *)[tableView cellForRowAtIndexPath:indexPath].accessoryView;
[tempSwitch addTarget:self action:@selector(SwitchToggle:) forControlEvents:UIControlEventValueChanged];
[tableView deselectRowAtIndexPath:indexPath animated:YES]; // cell selection fadeout animation
}
谢谢。
最佳答案
代码必须如下所示:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UISwitch *tempSwitch = (UISwitch *)[tableView cellForRowAtIndexPath:indexPath].accessoryView;
[tempSwitch setOn:!tempSwitch.on animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
请记住,您还必须更新模型。
关于objective-c - 调用 didSelectRowAtIndexPath 时激活单元格的附属 View (UISwitch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367985/