美文网首页
2020-04-07

2020-04-07

作者: 董亚强 | 来源:发表于2020-04-07 14:02 被阅读0次

iOS 13  黑夜模式适配 (runtime)

#import "UIView+UIView_Black.h"

@implementationUIView(UIView_Black)

+ (void)load

{

    staticdispatch_once_tonceToken;

    dispatch_once(&onceToken, ^{

        idobj = [[selfalloc]init];

        [objswizzleMethod:@selector(setBackgroundColor:)withMethod:@selector(blackSetBackgroundColor:)];

    });

}

- (void)blackSetBackgroundColor:(UIColor*)backgroundColor{

    if(@available(iOS13.0, *)) {

        UIColor*color = [UIColorcolorWithDynamicProvider:^UIColor*_Nonnull(UITraitCollection*_NonnulltraitCollection) {

            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {

                if(backgroundColor == [UIColorwhiteColor]) {

                    return[UIColorblackColor];

                }else{

                    if(backgroundColor) {

                        returnbackgroundColor;

                    }else{

                        return[UIColorclearColor];

                    }

                }

            }else{

                if(backgroundColor) {

                    returnbackgroundColor;

                }else{

                    return[UIColorclearColor];

                }

            }

        }];

        return [self blackSetBackgroundColor:color];

    }else{

        return[selfblackSetBackgroundColor:backgroundColor];

    }

}

- (void)swizzleMethod:(SEL)origSelectorwithMethod:(SEL)newSelector

{

    Classcls = [selfclass];

    MethodoriginalMethod =class_getInstanceMethod(cls, origSelector);

    MethodswizzledMethod =class_getInstanceMethod(cls, newSelector);

    BOOLdidAddMethod =class_addMethod(cls,

                                        origSelector,

                                        method_getImplementation(swizzledMethod),

                                        method_getTypeEncoding(swizzledMethod));

    if(didAddMethod) {

        class_replaceMethod(cls,

                            newSelector,

                            method_getImplementation(originalMethod),

                            method_getTypeEncoding(originalMethod));

    }else{

        method_exchangeImplementations(originalMethod, swizzledMethod);

    }

}

@end

相关文章

网友评论

      本文标题:2020-04-07

      本文链接:https://www.haomeiwen.com/subject/kutnphtx.html