即使traitCollection.userInterfaceStyle = Dark,也仅从[UIColor colorNamed:]返回的浅外观颜色

问题描述 投票:0回答:1

我正在为我的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,也仅返回浅色。

我想念什么吗?

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

ios objective-c uicolor ios-darkmode
1个回答
0
投票

您要从资产目录中获取的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];
© www.soinside.com 2019 - 2024. All rights reserved.