CALayer: insertSublayer() method
The insertSublayer() method inserts a layer at a given position among the sublayers.
Syntax
insertSublayer(layer, { atIndex })
insertSublayer(layer, { above })
insertSublayer(layer, { below })Parameters
layer
The layer to insert.
options.atIndex
The position in sublayers to insert at, an integer. 0 is the bottom.
options.above
An existing sublayer. Inserts directly above it.
options.below
An existing sublayer. Inserts directly below it.
Give one of the three options.
Return value
None (undefined).
Calling insertSublayer() again on a layer already in sublayers moves it to the new position; it doesn't add a second copy.
Exceptions
TypeError
- None of the three is given:
insertSublayer needs one of { atIndex } / { above } / { below }. layerisn't a layer:insertSublayer: expects a CALayer.aboveorbelowisn't a layer:insertSublayer: expects two CALayers.atIndexis negative:insertSublayer:atIndex: index must not be negative.atIndexdoesn't convert to a finite number:atIndex must be a finite number, got ….
Examples
js
const host = new CALayer();
const a = new CALayer();
const b = new CALayer();
const c = new CALayer();
host.addSublayer(a); // [a]
host.addSublayer(b); // [a, b], b above a
host.insertSublayer(c, { atIndex: 0 }); // [c, a, b], c at the bottom
host.insertSublayer(c, { above: b }); // [a, b, c], c moves above b
host.insertSublayer(c, { below: a }); // [c, a, b], c moves below aResult: The comment on each line shows host.sublayers after that line runs. Layers later in the array are drawn on top.
Corresponding iOS API
-[CALayer insertSublayer:atIndex:], -insertSublayer:above:, -insertSublayer:below:. The second part goes into the options object.
See also
addSublayer()zPosition: changes the stacking order without changing the array order