简体   繁体   中英

NSView and CALayer

On Cocoa, in order to ensure that a view has it's own layer, you should set wantsLayer to true .

What is the exact difference with wantsLayer and wantsUpdateLayer ?
From what I understand wantsLayer causes the view to start using a layer, while wantsUpdateLayer changes the way the view is drawn (by calling updateLayer instead of draw ).

What would be the use of setting wantsLayer to true without setting wantsUpdateLayer to true either ?
Do you still need to set wantsLayer to true if you have wantsUpdateLayer set to true ?

Where should I interact with my views layer ?
Is this right that you should only interact with your layer within the updateLayer function ? Does this applies to every property and method of CALayer ? For instance if I want to add a sublayer, should this be done in updateLayer too ?

EDIT Additionally, the latest AppKit release notes states that :

Apps targeting macOS 10.14 should prefer the wantsUpdateLayer property over the wantsLayer property.

So does this mean that on macOS 10.14 you don't actually need to use wantsLayer if you are already using wantsUpdateLayer ?

The wantsLayer property tells whether your NSView will be backed by a layer or not. By default NSViews are not layer backed by default. So if you need a layer (eg for animations), you need to specify it.

The wantsUpdateLayer is really different. NSView can update their content in two (exclusive) ways :

  • by calling the drawRect: method
  • by calling the updateLayer method

By default wantsUpdateLayer returns NO, and therefore, drawRect: is called. but if you set wantsUpdateLayer to return YES (and if your view is layer-backed), then updateLayer will be called instead.

updatelayer can be much faster than drawRect: if you can update your view content by modifying layer attributes

So to answer you questions :

  • You want to set wantsLayer to YES and wantsUpdateLayer to NO if you need to do fancy drawing in drawRect: (remember, updateLayer is faster but you can only modify the layer attributes)
  • Yes, you need wantsLayer to YES if you set wantsUpdateLayer to YES
  • You can interact with your layer attribute wherever you want, including from drawRect:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM