即使traitCollection.userInterfaceStyle = Dark,也仅从[UIColor colorNamed:]返回了亮色。

时间:2019-11-06 15:45:31

标签: ios objective-c uicolor ios-darkmode

我正在为iOS 11+应用程序添加iOS 13暗模式支持。在整个应用程序中使用命名/动态颜色效果很好。

但是,在自定义类中使用[UIColor colorNamed:]时,始终返回浅色版本(#ffffff /白色)而不是深色版本(#000000 /黑色):

// Some ViewController
CustomClass *custom = [customClass alloc] initWithTraitCollection:self.traitCollection]; 

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    custom.traitCollection = self.traitCollection;
}


// CustomClass
- (void)initWithTraitCollection:(UITraitCollection *)traitCollection {
    self = [super init];
    if (self) {
        self.traitCollection = traitCollection;
    }
    return self;
}

- (void)doSomething {    
    NSLog(@"CustomClass UIStyle: %@", (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark ? @"dark" : (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight ? @"light" : @"unspecified")));

    // Trying to get the color in three different ways (normal + specify traitCollection explicitly)
    UIColor *color1 = [UIColor colorNamed:@"whiteOrBlack"];
    UIColor *color2 = [UIColor colorNamed:@"whiteOrBlack" inBundle:nil compatibleWithTraitCollection:self.traitCollection];

    __block UIColor *color3 = color1;
    [self.traitCollection performAsCurrentTraitCollection:^{
         color3 = [UIColor colorNamed:@"whiteOrBlack"];
    }];

    // Output
    NSLog(@"   color1: %@", [self colorAsHexString:color1]);
    NSLog(@"   color2: %@", [self colorAsHexString:color2]);
    NSLog(@"   color3: %@", [self colorAsHexString:color3]);
}


// Output
CustomClass UIStyle: dark
   #ffffff
   #ffffff
   #ffffff

我是否明确指定traitCollection / UIUserInterfaceStyle都没关系。即使UIUserInterfaceStyleDark处于活动状态,也只返回浅色。

我缺少什么吗?

还有其他方法可以明确指定我要访问的颜色值吗?

1 个答案:

答案 0 :(得分:1)

您从资产目录中获取的UIColor是动态的。这意味着其RGB分量的值取决于[UITraitCollection currentTraitCollection]的值。每次您请求组件时,颜色都会根据currentTraitCollection自行解决。

您没有显示-colorAsHexString:方法的实现,但是必须以某种方式从颜色中获取RGB分量。

因此,您想在设置-colorAsHexString:时致电currentTraitCollection,如下所示:

    UIColor *dynamicColor = [UIColor colorNamed:@"whiteOrBlack"];

    [self.traitCollection performAsCurrentTraitCollection:^{
         NSLog(@"Color: %@", [self colorAsHexString:dynamicColor]);
    }];

(更好的是,您可以在performAsCurrentTraitCollection的实现中将对-colorAsHexString:的调用放在您的特定情况下。)

以下是为特定特征集获取解析的非动态颜色的方法:

    UIColor *dynamicColor = [UIColor colorNamed:@"whiteOrBlack"];
    UIColor *resolvedColor = [dynamicColor resolvedColorWithTraitCollection:self.traitCollection];