objective-c - 调用 didSelectRowAtIndexPath 时激活单元格的附属 View (UISwitch)

标签 objective-c ios uitableview uiswitch didselectrowatindexpath

我的 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/

相关文章:

objective-c - 使用绘图 View 缩放

ios - Admob非页内广告Cocos2d objective-c

ios - 当使用 UIApplicationLaunchOptionsLocationKey 在后台启动应用程序时,NSURLCredentialStorage 不返回任何凭据

ios - 引用超出范围的 UICollectionViewCell

objective-c - 在对象 'delegate' 上找不到属性 'AddEventViewController'

ios - 分组 UITableview 删除外部分隔线

ios - 设置 UIButton 的 titleLabel.font 属性不起作用

ios - 如何在 Apple WatchKit 中制作动画按钮?

ios - 调整 UITextView 高度以适应 UITableViewCell 中的文本

ios - UITableView 复选标记样式在选择时删除突出显示