I am creating a gradient layer and adding it to my MainViewController
self.view.
override func viewDidLoad() {
super.viewDidLoad()
gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = colors
view.layer.insertSublayer(gradient, at: 0)
}
Inside viewDidAppear
I am enumerating all the sublayers:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
for x in (view.layer.sublayers)! {
print(x)
}
}
This is what I get when I am running the app (which is normal):
<CAGradientLayer: 0x608000224120>
<_UILabelLayer: 0x60000009a400>
<_UILabelLayer: 0x60800009f180>
<CALayer: 0x600000422d60>
<CALayer: 0x608000223820>
Then from MainViewController
I present modally another vc and then dismiss it. After this MainVC viewDidAppear
is called again, but this time I get this:
<_UILabelLayer: 0x60000009a400>
<_UILabelLayer: 0x60800009f180>
<CALayer: 0x600000422d60>
<CALayer: 0x608000223820>
The CAGradientLayer
was removed from self.view. I can fix this by moving my code from viewDidLoad
to viewDidAppear
, but I want to understand why is the CAGradientLayer
removed, after the controller was dismissed.
I was unable to reproduce your situation in a simple test program.
Here is some debugging advice...
To find out where the gradient layer is being removed from view.layers
, define
class MyCAGradientLayer: CAGradientLayer {
deinit {
print("there it goes")
}
}
and replace your CAGradientLayer
with MyCAGradientLayer
which is created locally in viewDidLoad
.
override func viewDidLoad() {
super.viewDidLoad()
let gradient = MyCAGradientLayer()
gradient.frame = view.bounds
gradient.colors = colors
view.layer.insertSublayer(gradient, at: 0)
}
After viewDidLoad
finishes the local variable gradient
will release its reference to the gradient
and only one reference to the gradient
will exist (the one in the view.layers
array).
Set a breakpoint on the print
statement to see where it is getting freed.
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.