首页 > 解决方案 > 框架使用drawRect:; 我需要在支持层的 NSView 上使用它。如何更新?

问题描述

根据 NSView 的文档drawRect:

如果您的应用程序使用其图层对象管理内容,请使用 updateLayer 方法来更新您的图层,而不是覆盖此方法。

我有一个NSView框架提供的子视图,它们都使用drawRect:. 这个框架提供的视图是一个NSView我需要一个层的子视图。因为我的框架提供的视图是支持层的视图的后代,drawRect:所以通常不会被调用,尤其是在窗口处于活动或非活动状态的情况下(视图需要更新以反映其(非)活动状态)。

当然,如果我使包含视图不支持图层,则当窗口处于活动或非活动状态时会发生更新。

在不将框架修改为自定义分支的情况下,确保drawRect:在我的框架提供的视图中需要时发生的最佳途径是什么?

谢谢。

2018 年 8 月 25 日编辑:

看起来诀窍是将层次结构中的一个视图设置为,例如,[view setCanDrawSubviewsIntoLayer:YES根据文档,它使用所有子视图drawRect:将它们的绘图添加到它自己的层。然而,这似乎只在 10.13 中有效,并且在 10.14 测试版中被打破。我将继续寻找潜在的 API 更改,除非这是 10.14 beta 错误。

由于问题仍未解决,因此尚未真正回答。

标签: cocoacalayernsviewdrawrect

解决方案


Layer-backed views which don't override -wantsUpdateLayer to return true still draw themselves using -drawRect:. The bit of documentation you quoted is using "should" to mean "should, for best performance,". It's not required, it's just recommended.

Views don't generally redraw themselves just because the containing window has changed key or main status. You would have to mark them as needing display. Or the framework should be doing that.

I suspect the reason that it works when your view is not layer-backed is that you are marking your view as needing update. Since non-layer-backed views draw into the window's backing store using the painter model (back to front), if your view redraws itself then any subviews will have to redraw themselves on top of your view's drawing.

If the framework's views need to redraw when the window's key/main status changes, then they should be observing the relevant notifications and setting themselves as needing display. If they're not doing that, it's a framework bug. You can work around it by marking them as needing display yourself.


推荐阅读