Obj-C, how to iterate all views for views with font properties?

65 views Asked by At

I'm trying to initially survey (log) all the fonts and font sizes I use in my app, fonts / sizes, that could be set programmatically or in nib files. Afterwards, I hope to use the code to set fonts too.

(I am aware of font type dynamics, however I'm have auto layout issues.)

I've got so far (see below), but ideally I'd like to just find anything with a font, I mean it could be a navigation bar not just buttons, labels or textfields.

Maybe I could somehow check to so see if the font method was a available ?

NSArray* buttonsArray = currentView.subviews;

for((UIButton*) button in buttonsArray)
{
     button.titleLabel.font = [UIFont fontWithName:@"myCustomFont" size:16];
}
4

There are 4 answers

0
nielsbot On

You can check if an object responds to -font by sending it the -respondsToSelector: message, like this:

if ( [ obj respondsToSelector:@selector( font ) ] )
{
    UIFont * font = [ (id)obj font ] ;
}
0
siutsin On

You can assign if the setter of the font is responding:

Note: code didn't tested

for(id obj in buttonsArray)
{
    if ( [obj respondsToSelector:@selector(setFont:)] )
    {
        // do something
    }
}
2
skytoup On
[obj respondsToSelector:@selector(font)];

if the method is retuen YES,then meant obj has font method.

6
Eiko On

While asking if an object responds to font or setFont: is technically working, we now have the UIAppearance system, which are designed to give the app a consistent design. You can do things like "all my navigation bars should be green", or "all buttons should be blue, except those which are contained in .... which should be yellow". Many attributes are configureable, and setting this up is as easy as listing the desired appearance patterns for example in applicationDidLoad:.

http://nscookbook.com/2013/01/ios-programming-recipe-8-using-uiappearance-for-a-custom-look/ is one of the short introductions available on the net.

The good thing about using this instead of hacking something together while traversing your view tree is that it will work for all views, even those that you didn't create so far. If you set it manually, you have to do so after each view creation, which is tedious, wasteful and open to bugs. Also, you're less likely to break things that you didn't mean to, like third party classes.