【Cocoa】 Initializing View Instances Created in Interface Builder

Initializing View Instances Created in Interface Builder

View instances that are created in Interface Builder don't call initWithFrame: when their nib files are loaded, which often causes confusion. Remember that Interface Builder archives an object when it saves a nib file, so the view instance will already have been created and initWithFrame: will already have been called.

The awakeFromNib method provides an opportunity to provide initialization of a view when it is created as a result of a nib file being loaded. When a nib file that contains a view object is loaded, each view instance receives an awakeFromNib message when all the objects have been unarchived. This provides the object an opportunity to initialize any attributes that are not archived with the object in Interface Builder. The DraggableItemView class is extremely simple, and doesn't implementawakeFromNib.

There are two exceptions to the initWithFrame: behavior when creating view instances in Interface Builder. Its important to understand these exceptions to ensure that your views initialize properly.

If you have not created an Interface Builder palette for your custom view, there are two techniques you can use to create instances of your subclass within Interface Builder. The first is using the Custom View proxy item in the Interface Builder containers palette. This view is a stand-in for your custom view, allowing you to position and size the view relative to other views. You then specify the subclass of NSView that the view represents using the inspector. When the nib file is loaded by the application, the custom view proxy creates a new instance of the specified view subclass and initializes it using the initWithFrame: method, passing along any autoresizing flags as necessary. The view instance then receives an awakeFromNib message.

The second technique applies when your custom subclass inherits from a view that Interface Builder provides direct support for. To take advantage of Interface Builder’s built-in support, create an instance of the view that Interface Builder has direct support for, and then use the inspector to change the class name to your custom subclass. For example, you can create an NSScrollView instance in Interface Builder and specify that a custom subclass (MyScrollView) should be used instead, again using the inspector. In this case, when the nib file is loaded by the application, the view instance has already been created and the MyScrollView implementation of initWithFrame: is never called. The MyScrollView instance receives an awakeFromNibmessage and can configure itself accordingly.

 

posted @ 2015-03-13 14:59  rizo  阅读(204)  评论(0编辑  收藏  举报