Search
Recommended for You

Locating, tagging, and retrieving views


Last week, I wrote about exploring subviews both of the user-added and Apple-created varieties. Many GUI components contain view classes that are hidden from the developer but are composed of perfectly standard components. The UISwitch, for example, has two hidden UILabels which control the text displayed on the left and right. Should you wish to swap these from ON/OFF to YES/NO, all you need to do is tunnel down through the underlying private _UISwitchSlider class to access those labels.

Tagging allows you to recover subviews without drilling down. Once tagged, you can retrieve a view using [myView viewWithTag:TAGNUMBER] regardless of the view's position in the hierarchy. If you know the class you're looking for, and especially if there's only one of that class represented in the hierarchy, it becomes trivial to find and tag that view. Here, I search for a UIScroller and tag it with the SCROLLER_TAG that I have set in a #define statement.

for (UIView *view in [self.view subviews]) 
    if ([view isKindOfClass:[UIScroller class]]) 
        [view setTag:SCROLLER_TAG];

Tags are simply integers. You can assign any value. It helps to use #define's to add a semantic wrapping to the integer. To recover the view, use viewWithTag:. This always returns a (UIView *) so be sure to cast the view returned:

#define SCROLLER_VIEW	(UIScroller *) [self.view viewWithTag:SCROLLER_TAG]

Defining SCROLLER_VIEW this way cleans up my code a lot. For example, [SCROLLER_VIEW setOffset:offsetPoint]; lets me treat the view retrieval as a simple object, eliding messy details.

AddThis Social Bookmark Button
Comments (0)

Leave a comment