Why does my view move when I set its frame after changing its anchorPoint?

后端 未结 2 832
醉话见心
醉话见心 2020-12-08 12:19

I made two instances of UILabel and added them to my ViewController\'s view. And then I changed the anchorPoint of each from 0.5 to 1.

2条回答
  •  失恋的感觉
    2020-12-08 12:39

    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:

    anchor at center

    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:

    anchor at corner

    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:

    anchor at corner with reset frame

    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.

提交回复
热议问题