繁体   English   中英

Objective-C - 以编程方式更改渐变背景颜色 UIViewController 当 iOS 13 更改暗模式时

[英]Objective-C - Change programmatically Gradient Background Color UIViewController When iOS 13 Dark Mode changed

我正在我的应用程序中实现管理iOS 13 的暗模式的功能。我的 ViewController 的背景有问题。

我的观点 controller 具有使用CAGradientLayer获得的背景渐变色。

当它从暗模式--->亮模式和亮模式--->暗模式..

我的问题是,当用户在后台将我的应用程序发送到 go 到控制中心并更改模式时,我用于背景颜色的渐变的 colors 不会立即更改...

要获得渐变颜色更改,用户必须关闭应用程序并重新打开它。

一个非常糟糕的用户体验,所以我想问你如何解决这个问题......

这是我用来根据用户选择的iOS模式更改渐变的 colors 的方法

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupBackground];
}

- (void)setupBackground {

    UIColor *secondaryColor = self.view.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark ? UIColor.customRedColor : UIColor.customGreenColor;

    CAGradientLayer *gradient = [CAGradientLayer layer];

    gradient.frame = UIApplication.sharedApplication.windows.firstObject.bounds;
    gradient.colors = @[(id)UIColor.customBlueColor.CGColor, (id)secondaryColor.CGColor];
    gradient.locations = @[@0.1, @0.9];

    [self.view.layer insertSublayer:gradient atIndex:0];
}

您应该实现traitCollectionDidChange并让它更新您的背景:

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];

    if (@available(iOS 13.0, *)) { // Needed if your app supports iOS 12
        if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
            [self setupBackground];
        }
    }
}

当然这意味着setupBackground会被调用很多次。 所以你应该更新它,这样它就不会每次都添加一个新层。

凯恩,

在 iOS13 上使用 ObjC 实现暗模式有很多困难,但幸运的是,一群 Devs e 设计师做了一个非常简单的方法:

https://medium.com/flawless-app-stories/implementing-dark-mode-on-ios-d195cac098de

此致。 o/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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