Archive for June 22nd, 2010

Categories as Stylesheets

Here’s an interesting article on how to approach the problem of presenting unified interface adjustments, as in this problem you’ve probably encountered before:

… However, getting all the UI widgets to look similarly can be complex, particularly in large applications; what if your client or their designers change their minds about the font size or some background color right before shipping your project? Of course you can “search and replace” all occurrences of some color using Xcode, but you have the risk of leaving some unchanged widget somewhere. And believe me, this happens really often.

In this article I will discuss a simple approach, using Objective-C categories, to keep your styling information separated from the rest of the application, using a system that will be familiar to developers used to creating websites using CSS (Cascading Style Sheets).

The heart of it is to apply Objective-C niftiness by adding an NSObject category

… Why a category on NSObject? Because not everything you see on your iPhone screen is a subclass of UIView! UIBarButtonItems, for example, inherit from UIBarItem, which itself inherits from NSObject, and not from UIView. By the way, by extending NSObject, this code could also be used in Mac OS X applications, for example, without modification…

to add “cascadingStyle” property semantics

@implementation NSObject (AKCascadingStyle)

@dynamic cascadingStyle;

- (void)setCascadingStyle:(AKCascadingStyle *)style

{

   [style applyToObject:self];

}

- (id)cascadingStyle

{

   return [AKCascadingStyle styleFromObject:self];

}

@end

and polymorphism of -applyToObject and -styleFromObject takes care of the ‘cascading’ bits.

Certainly worth a look at the code on github!

Continue Reading →
2