|
| 1 | +import UIKit |
| 2 | + |
| 3 | +open class _StackLayerWrapperView: UIView { |
| 4 | + |
| 5 | + open override func didAddSubview(_ subview: UIView) { |
| 6 | + super.didAddSubview(subview) |
| 7 | + defer { |
| 8 | + subview.removeFromSuperview() |
| 9 | + } |
| 10 | + |
| 11 | + subview._fitSize(with: subview._stackKit_fitType) |
| 12 | + |
| 13 | + // Copy UIImageView |
| 14 | + if convertUIImageView(subview) { |
| 15 | + return |
| 16 | + } |
| 17 | + if convertDividerView(subview) { |
| 18 | + return |
| 19 | + } |
| 20 | + if convertSpacerView(subview) { |
| 21 | + return |
| 22 | + } |
| 23 | + convertViewToImage(subview) |
| 24 | + } |
| 25 | + |
| 26 | + private func convertUIImageView(_ subview: UIView) -> Bool { |
| 27 | + guard let imageView = subview as? UIImageView else { return false } |
| 28 | + let imageLayer = CALayer() |
| 29 | + |
| 30 | + // fix subview.layer.contents is nil below on iOS 15? |
| 31 | + // |
| 32 | + // test on iOS 14.3, subview.layer.contents is nil, |
| 33 | + // test on iOS 15, subview.layer.contents has some value. |
| 34 | + // ⚠️ ❌ imageLayer.contents = subview.layer.contents |
| 35 | + |
| 36 | + imageLayer.contents = imageView.image?.cgImage |
| 37 | + imageLayer.bounds = subview.layer.bounds |
| 38 | + imageLayer.backgroundColor = subview.backgroundColor?.cgColor |
| 39 | + layer.addSublayer(imageLayer) |
| 40 | + |
| 41 | + return true |
| 42 | + } |
| 43 | + |
| 44 | + /// override in subclass |
| 45 | + open func convertDividerView(_ subview: UIView) -> Bool { |
| 46 | + false |
| 47 | + } |
| 48 | + |
| 49 | + private func convertSpacerView(_ subview: UIView) -> Bool { |
| 50 | + guard let spacerView = subview as? SpacerView else { return false } |
| 51 | + |
| 52 | + let spacerLayer = spacerView.spacerLayer |
| 53 | + layer.addSublayer(spacerLayer) |
| 54 | + |
| 55 | + return true |
| 56 | + } |
| 57 | + |
| 58 | + private func convertViewToImage(_ subview: UIView) { |
| 59 | + // render view to image and create CALayer with it |
| 60 | + // |
| 61 | + // If you use `view.layer` directly, there may be problems with display, for example: `UILabel` -> `_UILabelLayer` cannot display text normally |
| 62 | + // 如果直接使用 view.layer 可能显示会有问题, 例如: UILabel -> _UILabelLayer 无法正常显示文字 |
| 63 | + let image = UIGraphicsImageRenderer(bounds: subview.bounds).image { context in |
| 64 | + subview.layer.render(in: context.cgContext) |
| 65 | + } |
| 66 | + let tempLayer = CALayer() |
| 67 | + tempLayer.contents = image.cgImage |
| 68 | + tempLayer.bounds = subview.bounds |
| 69 | + layer.addSublayer(tempLayer) |
| 70 | + } |
| 71 | + |
| 72 | + open override var intrinsicContentSize: CGSize { |
| 73 | + sizeThatFits(.zero) |
| 74 | + } |
| 75 | +} |
0 commit comments