gpt4 book ai didi

ios - 只有从 [UIColor colorNamed :] even though traitCollection. userInterfaceStyle = Dark 返回的浅色外观颜色

转载 作者:行者123 更新时间:2023-11-28 23:25:55 25 4
gpt4 key购买 nike

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

但是,在自定义类中使用 [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 处于事件状态,也仅返回浅色。

我错过了什么吗?

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

最佳答案

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

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

因此,您需要在设置 currentTraitCollection 时调用 -colorAsHexString:,如下所示:

    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];

关于ios - 只有从 [UIColor colorNamed :] even though traitCollection. userInterfaceStyle = Dark 返回的浅色外观颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58733875/

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