如何隐藏iPhone X的home指示灯在app委托中写一段常用代码

问题描述 投票:0回答:1

在我的项目中,我想隐藏主指示器,而不需要在每个视图控制器中写同样的代码,而是在appDelegate中实现它。我试过

   - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor yellowColor];
    return YES;
}

-(BOOL)prefersHomeIndicatorAutoHidden{
    return YES;
}

我试过这样做,但它不常见。那么,我怎样才能不在每个视图控制器中写代码,而在app delegate中实现隐藏原点指示器呢?

ios objective-c appdelegate
1个回答
1
投票

有一种方法可以实现这一点。在我看来,这不是最优雅的,我同意Gereon的说法,你最好创建一个子类 UIViewController在那里实现它,然后让你所有的视图控制器从这个基类继承。

然而,你可以使用Method Swizzling来实现。请看这里。https:/nshipster.commethod-swizzling。. 在你的情况下,你可以在AppDelegate中的Swizzle它。application: didFinishLaunchingWithOptions: 嗖嗖 prefersHomeIndicatorAutoHidden 到您的自定义函数,返回 YES.

所以对于swizzling我建议你新建一个UIViewController的Category。而实际的swizzling。

#import <objc/runtime.h>

@implementation UIViewController (Swizzling)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        SEL originalSelector = @selector(prefersHomeIndicatorAutoHidden);
        SEL swizzledSelector = @selector(swizzledPrefersHomeIndicatorAutoHidden);
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

        const BOOL didAdd = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (didAdd)
            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        else
            method_exchangeImplementations(originalMethod, swizzledMethod);
    });
}

- (BOOL)prefersHomeIndicatorAutoHidden
{
    return YES; //Doesn't matter what you return here. In this you could return the actual property value.
}

- (BOOL)swizzledPrefersHomeIndicatorAutoHidden //This is the actual `prefersHomeIndicatorAutoHidden ` call
{
    return YES;
}

@end
© www.soinside.com 2019 - 2024. All rights reserved.