旋转UILabel最优雅的方式; 保持左下角

Fat*_*tie 1 transformation uiview ios objective-c-category

假设您希望文本向上.当然,它很容易旋转90度:

someUIView.transform = CGAffineTransformMakeRotation(- 90.0f * M_PI / 180.0f);
Run Code Online (Sandbox Code Playgroud)

但通常情况下,你希望它保持左下角

因此,在故事板IB中,您可以将(水平)文本放在您想要左下角的位置,并且您希望在应用程序运行时,文本是垂直的,这是"新"左下角的位置垂直文本将是.

在此输入图像描述

这是UIView上的一个类别......

-(void)standOnBottomLeftCorner
    {
    CGPoint org = self.frame.origin;
    org.y += self.frame.size.height;
    self.transform = CGAffineTransformMakeRotation(- 90.0f * M_PI / 180.0f);
    CGRect nu = self.frame;
    nu.origin = org;
    nu.origin.y -= nu.size.height; 
    self.frame = nu;
    }
Run Code Online (Sandbox Code Playgroud)

但请注意:

JRT解释说:"你不应该在转换后的视图上设置框架,它是未定义的行为."

除非我喝醉了,否则有效.........但最好的方法是什么?


这个插图显示了Matic非常聪明的想法:

在此输入图像描述

jrt*_*ton 8

更改图层的锚点将改变变换工作点.

在你的情况下,你需要将锚点设置在标签的中间位置,将左侧的高度设置为一半,如Matic所指出的:

CGRect frame = self.frame;
self.layer.anchorPoint = CGPointMake((frame.size.height / frame.size.width * 0.5),0.5); // Anchor points are in unit space
self.frame = frame; // Moving the anchor point moves the layer's position, this is a simple way to re-set
CGAffineTransform rotate = CGAffineTransformMakeRotation(- 90.0f * M_PI / 180.0f); // Performs the rotation
self.transform = rotate;
Run Code Online (Sandbox Code Playgroud)

完成.您不应该在转换后的视图上设置框架,它是未定义的行为.