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][carmack] 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 cool[1]) 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];   
}

[carmack]: http://number-none.com/blow/john_carmack_on_inlined_code.html

[1]: [Answer by chown](http://stackoverflow.com/questions/2343432/how-to-get-uiview-hierarchy-index-i-e-the-depth-in-between-the-other-subvi

 
0
Kudos
 
0
Kudos

Now read this

Functional Programming - Perfectly Said

I have a half-written post sitting on my computer about my frustration regarding the conversation regarding functional programming and to a lesser degree regarding Swift. It was initially prompted by a conversation between Gordon... Continue →