0

I'm trying to rotate my UILabel 90 degrees about the left of the label, i.e.:

enter image description here

I originally did so using the following:

[self.copyrightLabel.layer setAnchorPoint:CGPointMake(0.0, 0.5)];
[self.copyrightLabel setTransform:CGAffineTransformMakeRotation(-M_PI / 2)];

But this causes my label to move to the centre of the screen:

enter image description here

I found this post and set it up but this has the same effect when I call:

[self setAnchorPoint:CGPointMake(0.0, 0.5) forView:_copyrightLabel]; 

Even if I don't rotate the UILabel it still gets moved:

enter image description here

Obviously the anchor point is working correctly but why does it move to the centre?

I'm using autolayout with three constraints, leading, trailing and bottom spaces.

Community
  • 1
  • 1
Leon
  • 3,614
  • 1
  • 33
  • 46

1 Answers1

0

Remove the trailing constraint on the label. It is causing your rotated label to extend across the full width of its superview. You only need to constrain the leading and bottom edges of the label, as the label's intrinsic content size will ensure it adapts to fit its content.

johnpatrickmorgan
  • 2,372
  • 2
  • 13
  • 17
  • I tried that soon after my post. The effect was the label now sits in the centre of the width of the label dependant on the length of the text. – Leon Jul 15 '15 at 15:58
  • I see. You might want to subclass `UILabel`, setting the transform, and overriding `intrinsicContentSize` to switch width and height. – johnpatrickmorgan Jul 15 '15 at 17:34
  • Or constrain your label's top, leading and bottom to its superview and give it a small constrained width, so that its frame will be suitable for when its text is rotated. It will look wrong in Interface Builder but will look correct at runtime. – johnpatrickmorgan Jul 15 '15 at 21:56
  • I can't do the latter suggestion because I want the label to be rotated dependant on the view behind it. For some it'll be horizontal and others vertical. – Leon Jul 16 '15 at 09:21
  • Then you should either add 2 labels, or create your own subclass of UILabel, adding the option to rotate it. You would need to override `intrinsicContentSize`, and call `invalidateIntrinsicContentSize` after you change the label's transform. – johnpatrickmorgan Jul 16 '15 at 14:48
  • I tried your suggestion of using a small constrained width and this made the width and height adjust to the same constraint. I tried a few other tweaks but to no avail. I've now found another way of displaying my text so I no longer need to get this working. Thanks a lot for your help though. – Leon Jul 21 '15 at 16:25