Tuesday, March 16, 2010

Tips to Use Interface Builder As Much As Possible

The Interface Builder of the XCode Suite is particularly powerful. It is very handy when developing for iPhone/iPod touch. However, it comes with some difficulty when you actually want to generate and place your widget programmingly. For example: you have a scroll view with several buttons inside that align vertically, however the number of buttons and the texts on them are decided at run-time so you can't simply drag some in using Interface Builder. But neither do you want to go after all these tedious API calls to create buttons then configure formats manually either; what then?

You can actually design a "sample button" using Interface Builder, have all the formats done (which is nice and easy using IB), then put it at the root of the widget hierarchy. Since it is not a sub-view of any other widgets, it is not shown at run-time. Then you can use the following code to copy this button as you want, place it anywhere you want, without worrying the format:

NSData *archived = [NSKeyedArchiver archivedDataWithRootObject: button_sample];
//Initiate buttons based on a sample
UIButton* b = [NSKeyedUnarchiver unarchiveObjectWithData: archived];
//set text, change position...
...

No comments:

Post a Comment