Steve Oliver
Steve Oliver

Reputation: 53

Subviews not displaying when using replaceSubview:with:

I'm writing a dynamic wizard application using cocoa/objective c on osx 10.6. The application sequences through a series of views gathering user input along the way. Each view that is displayed is provided by a loadable bundle. When the app starts up, a set of bundles are loaded and as the controller sequences through them, it asks each bundle for its view to display. I use the following to animate the transition between views

[[myContentView animator] replaceSubview:[oldView retain] with:newView];

This works fine most of the time. Every once in a while, a view is displayed and some of the subviews are not displayed. It may be a static text field, a checkbox, or even the entire set of subviews. If, for example, a checkbox is not displayed, I can still click where it should be and it then gets displayed.

I thought it might have something to do with the animation so I tried it like this

[myContentView replaceSubview:[oldView retain] with:newView];

with the same result. Any ideas on what's going on here? Thanks for any assistance.

Upvotes: 3

Views: 1254

Answers (2)

Theo
Theo

Reputation: 464

I got the same problem, replaceSubview didn't work. Finally i found something wrong with my code. so here are the rules :

  1. Both subviews should be in MyContentview's subviews array.
  2. OldView should be the topmost subview on MyContentView or replacesubview will not take place.

here is a simple function to perform replacesubview

- (void) replaceSubView:(NSView *)parentView:(NSView *)oldView:(NSView *)newView {
    //Make sure every input pointer is not nill and oldView != newView
    if (parentView && oldView && newView && oldView!=newView) {

        //if newview is not present in parentview's subview array
        //then add it to parentview's subview
        if ([[parentView subviews] indexOfObject:newView] == NSNotFound) {
            [parentView addSubview:newView];
        }

        //Note : Sometimes you should make sure that the oldview is the top
        //subview in parentview. If not then the view won't change.
        //you should change oldview with the top most view on parentview

        //replace sub view here
        [parentView replaceSubview:oldView with:newView];
    }
}

Upvotes: 1

Rodrigo
Rodrigo

Reputation: 12693

I don't think is good to use this [oldView retain]. This retain do not make sense. The function replaceSubview will retain it if it is necessary.

Because it work "most of the time" I think it is a memory problem. You try to use a released thing. Test without it and see what happens.

Upvotes: 1

Related Questions