简体   繁体   中英

Why can't I assign a UIView to self.view?

This might be a stupid question, but I'll shoot.

I made a little test project to test out a concept I had for a sliding view controller type of thing. I naively assumed I could create a UIView (let's call it peekView) with an outlet in a controller, and call something like [slidingControllerSlideFrom:self.view] from any visible view controller, the implementation of such being:

- (void)slidingControllerSlideFrom(UIView*)controllersMainView
{
    // push side controller to top of navigation stack

    self.peekView = controllersMainView;

    // sliding animation

}

But there is no effect. No crash, no warning, no change of view in the pushed controller. Of course, the pushed controller crashes when trying to add self's view as a subview, but assigning it to a predefined UIView just results in nothing.

So, why? And if a mere 'why' is not enough of a question- what happens when I try to assign one controller's view another controller's subview, and what was the reason for designing UIKit where you cannot set views from self.view ?

To do that you have two options:

1 - If the controller in the peekView is always the same one in a given scene, use a "Container View". Those are explained here . Basically, they allow you to add a view in your scene that is managed by another controller.

2 - If the controller in the peekView depends on different conditions, you will have to create something similar to a custom tabbarcontroller. That means that you instantiate the controller that you need, add it's view as a subview of peekView (not assign the controller's view to the peekView itself) and then use didmovetoparentviewcontroller to notify the child controller. This question might help.

UPDATE:

Just saw your comment, so let me answer what you actually asked: The peekview property is actually just a reference to the real UIView you placed in the screen. When you do this:

self.peekView = controllersMainView;

You are changing the reference, but no the view object itself. That's why you are not seeing any changes. There are ways of adding a new view to the controller from code, but it is much simpler to simply use addSubview to add your controllers view to a UIView that is already in the controller.

Check out the discussion here: subView Slide up from bottom of the screen and here: SubView slide in animation, iphone

Hopefully that gives you a bit of framework on how to approach this task!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM