Reputation: 15676
Three layers are given the same parent, but the zPosition value on the first layer to be added has no effect - it remains at the back. Why is this? The book I'm reading says that the position in the sublayers array can be overridden with the zPosition value.
import UIKit
import PlaygroundSupport
extension CGRect {
init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {
self.init(x:x, y:y, width:w, height:h)
}
}
let v0 = UIView(frame: CGRect(0, 0, 500, 500))
v0.backgroundColor = .white
let v1 = UIView(frame: v0.frame)
let lay1 = CALayer()
lay1.backgroundColor = UIColor(red: 1, green: 0.4, blue: 1, alpha: 1).cgColor
lay1.frame = CGRect(113, 111, 132, 194)
lay1.zPosition = 100
v1.layer.addSublayer(lay1)
let lay2 = CALayer()
lay2.backgroundColor = UIColor(red: 0.5, green: 1, blue: 0, alpha: 1).cgColor
lay2.frame = CGRect(41, 56, 132, 194)
v1.layer.addSublayer(lay2)
let lay3 = CALayer()
lay3.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1).cgColor
lay3.frame = CGRect(43, 197, 160, 230)
v1.layer.addSublayer(lay3)
v0.addSubview(v1)
PlaygroundPage.current.liveView = v0
Upvotes: 2
Views: 1368
Reputation: 15676
Code works as expected in an app. Seems that it's an issue with Playground.
Upvotes: 0
Reputation: 9484
I think your code is working as expected. I just changed the colors of the view to
lay1.backgroundColor = UIColor.green.cgColor
lay2.backgroundColor = UIColor.blue.cgColor
lay3.backgroundColor = UIColor.red.cgColor
This is the output. You can see green view(lay1) which has z position is at the top.
Also , had fun playing with literals here:
Upvotes: 3