Initializing View Instances Created in Interface Builder

来源:互联网 发布:前锦网络2018校园招聘 编辑:程序博客网 时间:2024/06/07 02:14

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 implement awakeFromNib.

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 is to specify a custom class is used when your custom view subclass inherits from a view that Interface Builder provides support for directly. 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. TheMyScrollView instance receives an awakeFromNib message and can configure itself accordingly.