How to show a uiview alway on top?

2019-06-13 16:48发布

问题:

I want to show a logo UIView always on top when the app running, I know there is a way to do that,add same UIView to every UIViewController, but I think this is not the best way to do that. when i have lot of pages,and modify the logo UIView,must modify it every page.

Did someone have better way to do this? thanks.

look like this:

回答1:

Since you only every have one window per app, and view's don't have levels, you have to make sure that view stays on top of the hierarchy, no matter what. One relatively easy way is to add it directly to the window above the rest of the interface (the navigation controller):

In applicationDidLaunch:

// After the main navigation controller or tab controller has been added
// either programmatically or in the xib:
UIImage *logo = [UIImage imageNamed:@"logo.png"];
UIImageView *logoView = [[UIImageView alloc] initWithImage:logo];
[self.window addSubview:logoView];


回答2:

Actually, I think that (a) creating a subclass of UIView that shows your logo and has all the necessary setup in it and then (b) adding this subclass to each view controller is the cleanest and most manageable way to do this.

The reason I prefer this method over adding the view to the window is because if you ever have a view that you don't want to show the logo, you won't need to show and hide something you added to the window. Also, adding directly to the window may cause rotation challenges on certain iOS devices in my experience, depending on what you're doing.

Also, to make sure your logo view is always on top of the view hierarchy, you can do two things:

  1. If the view already exists, you can bring it to front using [UIView bringSubviewToFront:]

    [myParentView bringSubviewToFront:myLogoSubview];
    
  2. If you are creating the view, it will be on top when you add it with [UIView addSubview:]

    // Set up myLogoSubview first here with alloc+init, etc.
    [myParentView addSubview:myLogoSubview];`
    

It looks like in your image you would replace myParentView with self.view and myLogoSubview with the view you're looking to keep on top, but this is just my assumption based on your image.