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.0 (x and y).
Next, I reset the frame of uiLabel2 to its frame I created it with: (100,100,100,20).
When I run the app, uiLabel1 and uiLabel2 show at different positions. Why?
UILabel *uiLabel1 = [[[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 20)] autorelease];
uiLabel1.text = @"UILabel1";
uiLabel1.layer.anchorPoint = CGPointMake(1, 1);
UILabel *uiLabel2 = [[[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 20)] autorelease];
uiLabel2.text = @"UILabel2";
uiLabel2.layer.anchorPoint = CGPointMake(1, 1);
uiLabel2.frame = CGRectMake(100, 100, 100, 20);
[self.view addSubview:uiLabel1];
[self.view addSubview:uiLabel2];

A
CALayerhas four properties that determine where it appears in its superlayer:position(which is the same as the view’scenterproperty)bounds(actually only thesizepart ofbounds)anchorPointtransformYou will notice that
frameis not one of those properties. Theframeproperty is actually derived from those properties. When you set theframeproperty, the layer actually changes itscenterandbounds.sizebased on the frame you provide and the layer’s existinganchorPoint.You create the first layer (by creating the first
UILabel, which is a subclass ofUIView, and everyUIViewhas 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.