View Hierarchy Recursion

Just a couple notes here, nothing earth shattering.

If you have a custom UITableViewCell with controls of some sort and you want to know in which cell a the value of a control changed, there are a few ways, one of which is bad, one of which is good.

bad:

UITableViewCell *cell = controlItem.superview;

This is dependent on the framework implementation at the time and in fact does not work for iOs 7 & 8. In those versions you would use:

controlItem.superview.superview

The fragility of this is obvious, especially if you’re not thinking and implement it on a custom UITableViewCell that has a different hierarchy.

A typically better way to approach the problem is some form of this:

- (UITableViewCell *)cellForControl:(UIControl *)control {  
    while (view != nil) {  
        if ([view isKindOfClass:[UITableViewCell class]]) {  
            return view;  
        }  
        view = view.superview;  
    }  
    return view; //will be nil  
}  

Lately (along with the rest of the iOs/OsX community), have been trying to think more “functional"ly about my code, so I am trying to minimize reference to properties within functions or methods, and have been trying at least to think about using recursion whenever I see loops these days. This problem lends itself to an obvious recursion. I searched but I haven’t seen this done around SO anywhere, though I did find this approach used in a slightly different (and cool1) context. Regardless, here is a recursive method to find the parent cell of a view:

- (UITableViewCell *)cellContainingView:(UIView *)view {  
    if (view == self.view) { //this could also be a nil check
        return nil;  
    }  
    return ([view isKindOfClass:[UITableViewCell class]]) ? view : [self funcCellContainingView:view.superview];  
}

I actually posted this version as a gist, which depends on finding no view, rather than self.view:

- (UITableViewCell *)cellContainingView:(UIView *)view {  
    return (!view || [view isKindOfClass:[UITableViewCell class]]) ? (UITableViewCell *)view : [self cellContainingView:view.superview];   
}
 
0
Kudos
 
0
Kudos

Now read this

Short  Watch Thoughts - II

Watch Paradigm The Apple watch is best when it hues to this analogy: Apple Watch : Information :: Watch : Time Things that follow from this paradigm: It must deliver information quickly. Almost instantly. I should never “feel the burn”... Continue →