我在自定义单元格中有一个开关。开关被分配并设置到自定义单元格的 .m 文件内的单元格的 accessoryView。
但是,我需要在自定义单元格所在的 tableView 的 ViewController 中处理开关的选择器方法。
目前,当我点击开关时,我遇到了找不到选择器的崩溃,很可能是因为它在单元格的 .m 中查找。
如何声明我的开关以使其选择器位于正确的位置?
根据要求编辑...
//cell .m
- (void)setType:(enum CellType)type
{
if (_type == SwitchType)
{
UISwitch *switchView = [[UISwitch alloc] init];
[switchView addTarget:self action:@selector(flip:) forControlEvents:UIControlEventValueChanged];
self.accessoryView = switchView;
}
}
最佳答案
听起来像是 delegate 的工作.在您的单元接口(interface)中创建一个协议(protocol),例如:
@protocol MyCellDelegate <NSObject>
- (void)myCell:(MyCell *)sender switchToggled:(BOOL)value;
@end
并指定一个委托(delegate)
id <MyCellDelegate> delegate;
然后在您的 MyCell.m 中,当切换开关时检查委托(delegate)是否已定义,如果已定义则调用它:
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(myCell:switchToggled:)]) {
[self.delegate myCell:self switchToggled:switch.value]
}
并且在您的 ViewController 中确保将 ViewController 设置为单元格的委托(delegate)并实现协议(protocol)方法。
关于ios - 自定义单元格内对象的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15508068/