开发者

Add an existing view with a nib file in another view through Interface Builder

开发者 https://www.devze.com 2023-01-23 20:58 出处:网络
I have a nib file say TestView.xib. I added some components to it. Now I created another nib file AnotherTestView.xib

I have a nib file say TestView.xib. I added some components to it.

Now I created another nib file AnotherTestView.xib

I want to add the view of TestView.xib into AnotherTestView.xib using interface buidler, so that I dont need to add the same components from TestView开发者_如何学Go again. They are like basic components for all my views.

Is there any way to do that. Like can we set the nib file name for a UIView in IB. Or how can we add this existing view which has a nib file into another nib file.


I wrote up how we embed custom-view Nibs inside other Nibs in a longish blog post. The crux is overriding -awakeAfterUsingCoder: in your custom view, replacing the object loaded from AnotherTextView.xib with the one loaded from the "embedded" Nib (TestView.xib).

Something along these lines:

// TestView.m
- (id) awakeAfterUsingCoder:(NSCoder*)aDecoder {
    BOOL theThingThatGotLoadedWasJustAPlaceholder = ([[self subviews] count] == 0);
    if (theThingThatGotLoadedWasJustAPlaceholder) {
        // load the embedded view from its Nib
        TestView* theRealThing = nil;
        NSArray* elements = [[NSBundle mainBundle] loadNibNamed: NSStringFromClass([TestView class])
                                                          owner: nil
                                                        options: nil];
        for (id anObject in elements) {
            if ([anObject isKindOfClass:[TestView class]]) {
                theRealThing = anObject;
                break;
            }
        }

        // pass properties through
        theRealThing.frame = self.frame;
        theRealThing.autoresizingMask = self.autoresizingMask;

        [self release];
        self = [theRealThing retain];
    }
    return self;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消