iOS Core Animation: CALayer bringSublayerToFront?

前端 未结 8 1692
情深已故
情深已故 2020-12-25 12:28

How do I bring a CALayer sublayer to the front of all sublayers, analogous to -[UIView bringSubviewToFront]?

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 12:42

    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()
    

提交回复
热议问题