How do I bring a CALayer sublayer
to the front of all sublayers, analogous to -[UIView bringSubviewToFront]
?
Swift 4 version.
Idea that layer itself has bringToFront
and sendToBack
methods.
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
extension CALayer {
func bringToFront() {
guard let sLayer = superlayer else {
return
}
removeFromSuperlayer()
sLayer.insertSublayer(self, at: UInt32(sLayer.sublayers?.count ?? 0))
}
func sendToBack() {
guard let sLayer = superlayer else {
return
}
removeFromSuperlayer()
sLayer.insertSublayer(self, at: 0)
}
}
Usage:
let view = NSView(frame: ...)
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.gray.cgColor
let l1 = CALayer(...)
let l2 = CALayer(...)
view.layer?.addSublayer(l1)
view.layer?.addSublayer(l2)
l1.bringToFront()