A CALayer
has four properties that determine where it appears in its superlayer:
position
(which is the same as the view's center
property)
bounds
(actually only the size
part of bounds
)
anchorPoint
transform
You will notice that frame
is not one of those properties. The frame
property is actually derived from those properties. When you set the frame
property, the layer actually changes its center
and bounds.size
based on the frame you provide and the layer's existing anchorPoint
.
You create the first layer (by creating the first UILabel
, which is a subclass of UIView
, and every UIView
has a layer), giving it a frame of 100,100,100,20. The layer has a default anchor point of 0.5,0.5. So it computes its bounds as 0,0,100,20 and its position as 150,110. It looks like this:
Then you change its anchor point to 1,1. Since you don't change the layer's position or bounds directly, and you don't change them indirectly by setting its frame, the layer moves so that its new anchor point is at its (unchanged) position in its superlayer:
If you ask for the layer's (or view's) frame now, you will get 50,90,100,20.
When you create the second layer (for the second UILabel
), after changing its anchor point, you set its frame. So the layer computes a new position and bounds based on the frame you provide and its existing anchor point:
If you ask the layer (or view) for its frame now, you will get the frame you set, 100,100,100,20. But if you ask for its position (or the view's center), you will get 200,120.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…