I'm adding a switch to contentView, and the contentView belongs to the cell. I'm trying to get the row number of the cell which has the switch triggered.
Here's the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
}
UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[cell addSubview:theSwitch];
cell.accessoryView = theSwitch;
[theSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
return cell;
}
- (void) switchChanged:(UISwitch *)sender {
UITableViewCell *theParentCell = [[sender superview] superview]; // Throwing Warning here
NSIndexPath *indexPathOfSwitch = [mainTableView indexPathForCell:theParentCell];
NSLog(@"the index path of the switch: %ld", (long)indexPathOfSwitch.row);
}
Here is the warning message:
Warning: "Incompatible pointer types initializing UITableViewCell * with an expression of type UIView *"
What the sender should be instead of superview?
If I understand correctly you are trying to get the switch parent cell index.
-(NSIndexPath *)indexPathWithSubview:(UIView *)subview {
while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
subview = subview.superview;
}
return [self.mytable indexPathForCell:(UITableViewCell *)subview];
}
- (void) switchChanged:(UISwitch *)sender {
NSIndexPath *apath = [self indexPathWithSubview:(UISwitch *)sender];
}
I recently ran across this. Here is the swift equivalent code
func indexPathWithSubview(subview: UIView) -> NSIndexPath {
var view = subview
while view.isKindOfClass(UITableViewCell) {
view = view.superview!
}
return tableView.indexPathForCell(view as! UITableViewCell)!
}
func switchChanged(sender: UISwitch) {
let indexPath = indexPathWithSubview(sender)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With