gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:26:39 24 4
gpt4 key购买 nike

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

我的 View Controller 具有使用 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];
}

最佳答案

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

关于ios - Objective-C - 当 iOS 13 黑暗模式改变时以编程方式改变渐变背景颜色 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58141937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com