Search code examples
iosuitableviewios7

Searching for a superview inside UITableViewCell iOS7


I had a custom UItableViewCell class named EditableTableViewCell that (besides other things) has a UITextField inside added to its contentView. In the Textfield delegate method I'm trying to detect to which section it belongs to. Like this:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    UIView* contentView =[textField superview];
    //traverse up in the view hierarchy until we find the cell's content view.
    while (![contentView isKindOfClass:[EditableTableViewCell class]] || contentView.superview == nil) {
        contentView = [contentView superview];
    }
    EditableTableViewCell *thiscell = (EditableTableViewCell*)contentView;
    NSIndexPath *indexpath =[[self tableView]indexPathForRowAtPoint:thiscell.center];

This gives me the correct result and I saw a similar solution here that also navigates the view hierarchy. I'm wondering if this is the only solution or if there's something more appropriate that doesn't involve looping for all the available cells.


Solution

  • Try this, no need to loop through the view

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
        UIView* contentView =[textField superview];
        CGPoint center = [self.tableView convertPoint:textField.center fromView:contentView];
        NSIndexPath *indexpath =[[self tableView] indexPathForRowAtPoint:center];
        NSLog(@"indexPath:%@", indexpath);
    }