Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
Like this article? We recommend

Delegates Can Alter Appearance

In addition to being able to control whether an object should be selected or editable, a delegate can be responsible for the appearance or display of an object. In NSBrowser, for instance, there is a delegate method (browser:willDisplayCell:atRow:column:). This method is called just before each cell in the browser is displayed. In this method, a delegate can decide to change how the cell looks when it gets drawn:

- (void)browser:(NSBrowser *)browser willDisplayCell:(id)cell atRow:(int)row column:(int)column {
 [cell setTitle:[NSString stringWithFormat:@"Cell at Row: %i, Col: %i", row, column]];
}

For this browser, each cell will display its row and column when it is drawn. Other attributes can be set during the execution of this method as well, including whether the cell is a leaf, the font used, whether the cell displays an image, and so on. See the documentation on NSCell for more information on what can be configured.

Although Java does not have a counterpart to NSBrowser (except for the version provided by Apple), similar functionality can be built using a combination of JTree and JTable. However, the amount of code required is quite extensive and beyond the scope of this article. In a JTable, it is normal to extend the cell renderer if you need dynamic functionality. With a delegate, this class extension can be avoided.

A large number of the Cocoa components have delegates that serve this same purpose. They give the developer an opportunity to set properties on the component before it is drawn to the screen. Window titles can be altered, sizes and positions can be changed—just about any property can be set by the delegate without a need to extend any of the classes.

  • + Share This
  • 🔖 Save To Your Account