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

标签 ios objective-c uiviewcontroller uicolor ios-darkmode

我正在我的应用中实现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/

相关文章:

ios - 自定义 UITableViewCell 内的水平 UIScrollView - 使用 IB Storyboard - 不滚动

iphone - 登录注销 View Controller

android - 使用按钮 appcelerator 推送通知(Android 和 iOS)

iOS - 在静态单例类中保留对主 UIViewController 的引用

ios - 使用AWSContinuationBlock发送兼容的指针 block 类型

ios - 改变 LeveyPopListView 的起点

iphone - 在 iphone 中搜索来自 PDF 的单词

swift - 惰性初始化变量持有函数 swift

ios - 如何避免 viewWillAppear 和 viewDidAppear 之间的延迟

ios - 获取 iPhone 相机胶卷中视频的 GPS 坐标