Multiple views in a UIWindow

前端 未结 3 1911
北海茫月
北海茫月 2021-01-06 18:47

I have a \"navigation based application\" which also needs to have a view always displayed at the bottom of the screen at all times. I added this new view to a UIWindow afte

3条回答
  •  死守一世寂寞
    2021-01-06 19:22

    If you add a view of another view controller as a subview to the active window of the application you must synchronize its center, bounds and transform properties with window.rootViewController.view. Also be sure your top view is added after correct initialization of the window, and also after its root subview has been added to it as a subview.

    I suppose this can be done in multiple ways, I've made it work through use of Key-value observing.

    Here the topViewController is instance of a UIViewController subclass and it represents the view controller of the UIView that should be on top of the application window

    AppDelegate.m:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [self.window.rootViewController.view addObserver:topViewController forKeyPath:@"transform" options:NSKeyValueObservingOptionNew context:@"rootView"];
        [self.window.rootViewController.view addObserver:topViewController forKeyPath:@"center" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"rootView"];
        [self.window.rootViewController.view addObserver:topViewController forKeyPath:@"bounds" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"rootView"];
        return YES;
    } 
    

    topViewController's .m file:

    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if([(__bridge_transfer NSString*)context isEqualToString:@"rootView"])
        {
            if([keyPath isEqualToString:@"transform"])
            {
                self.view.transform = [[change objectForKey:NSKeyValueChangeNewKey] CGAffineTransformValue];
            }
            else if ([keyPath isEqualToString:@"center"]) 
            {
                self.view.center = [[change objectForKey:NSKeyValueChangeNewKey] CGPointValue];
            }
            else if ([keyPath isEqualToString:@"bounds"]) 
            {
                self.view.bounds = [[change objectForKey:NSKeyValueChangeNewKey] CGRectValue];
            }
            else 
            {
                [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
            }
        }
        else 
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    

提交回复
热议问题