我试图通过切换NSViewController中的暗/光模式来改变图像的颜色。我使用这个代码来改变图像的颜色:
- (NSImage *)image:(NSImage *)image withColour:(NSColor *)colour
{
NSImage *img = image.copy;
[img lockFocus];
[colour set];
NSRect imageRect = NSMakeRect(0, 0, img.size.width, img.size.height);
NSRectFillUsingOperation(imageRect, NSCompositingOperationSourceAtop);
[img unlockFocus];
return img;
}我尝试过从viewWillLayout调用这个方法
self.help1Image.image = [self image:self.help1Image.image withColour:[NSColor systemRedColor]];但是系统颜色似乎总是返回相同的RGB值。
我也尝试过侦听通知AppleInterfaceThemeChangedNotification,但是即使在这里,RGB值似乎仍然是相同的1.000000 0.231373 0.188235。
[[NSDistributedNotificationCenter defaultCenter] addObserverForName:@"AppleInterfaceThemeChangedNotification"
object:nil
queue:nil
usingBlock:^(NSNotification * _Nonnull note) {
NSLog(@"AppleInterfaceThemeChangedNotification");
self.help1Image.image = [self image:self.help1Image.image withColour:[NSColor systemRedColor]];
NSColorSpace *colorSpace = [NSColorSpace sRGBColorSpace];
NSColor *testColor = [[NSColor systemBlueColor] colorUsingColorSpace:colorSpace];
CGFloat red = [testColor redComponent];
CGFloat green = [testColor greenComponent];
CGFloat blue = [testColor blueComponent];
NSLog(@"%f %f %f", red, green, blue);
}];我在NSButtonCell子类和重写layout中工作很好,但无法在NSViewController中工作
发布于 2019-07-12 18:13:23
首先,检查文档部分“使用特定方法更新自定义视图”这里。上面写着:
当用户更改系统外观时,系统会自动要求每个窗口和视图重新绘制自己。在此过程中,系统将为macOS和iOS调用几个著名的方法(下表中列出)来更新内容。系统在调用这些方法之前更新了特性环境,因此如果您在这些方法中进行了所有外观敏感的更改,则应用程序将正确地更新自己。
但是,该表中没有列出任何NSViewController方法。
由于视图的外观可以独立于当前或“系统”外观,所以对视图控制器中的外观更改作出反应的最佳方法是使用视图的effectiveAppearance属性,或者在[NSView viewDidChangeEffectiveAppearance]中做一些事情。
- (void)viewDidLoad
{
[self addObserver:self forKeyPath:@"view.effectiveAppearance" options:0 context:nil];
}
// ...
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
if ([keyPath isEqualToString:@"view.effectiveAppearance"])
{
// ...NSAppearance具有独立于系统外观的currentAppearance属性,并由Cocoa在上面列出的方法中进行更新。在其他任何地方,你都需要检查自己是否正确。惯用的方式还是通过视图的effectiveAppearance
[NSAppearance setCurrentAppearance:someView.effectiveAppearance];因此,在您的例子中,以下内容对我很有用:
- (void)viewDidLoad
{
[super viewDidLoad];
[self addObserver:self forKeyPath:@"view.effectiveAppearance" options:0 context:nil];
}
-(void)viewDidLayout
{
self.help1Image.image = [self image:self.help1Image.image withColour:[NSColor systemRedColor]];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"view.effectiveAppearance"])
{
[NSAppearance setCurrentAppearance:self.view.effectiveAppearance];
self.help1Image.image = [self image:self.help1Image.image withColour:[NSColor systemRedColor]];
}
}https://stackoverflow.com/questions/56968587
复制相似问题