2

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

我的视图控制器具有使用CAGradientLayer.

我设法根据用户的选择更改构成渐变的颜色,当它从暗模式 ---> 亮模式亮模式 ---> 暗模式..

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

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

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

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

- (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];
}
4

2 回答 2

2

您应该实施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会被调用很多次。所以你应该更新它,这样它就不会每次都添加一个新层。

于 2019-09-27T22:36:37.060 回答
0

凯恩,

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

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

此致。o/

于 2020-01-27T14:16:21.467 回答