I am putting my answer in a similar format to this answer.
Here is the original label:
Rotate 90 degrees clockwise:
yourLabelName.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
Rotate 180 degrees:
yourLabelName.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
Rotate 90 degrees counterclockwise:
yourLabelName.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
Do the same thing to rotate a button. Thankfully the touch events also get rotated so the button is still clickable in its new bounds without having to do anything extra.
yourButtonName.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2)
Notes:
Documentation for CGAffineTransform
The basic format is CGAffineTransform(rotationAngle: CGFloat)
where rotationAngle
is in radians, not degrees.
There are 2π radians in a full circle (360 degrees). Swift includes the useful constant CGFloat.pi
.
CGFloat.pi
= π = 180 degrees
CGFloat.pi / 2
= π/2 = 90 degrees
Auto Layout:
Auto layout does not work with rotated views. (See Frame vs Bounds for an explanation why.) This problem can be solved by creating a custom view. This answer shows how to do it for a UITextView
, but it is the same basic concept for a label or button. (Note that you will have to remove the CGAffineTransformScale
line in that answer since you don't need to mirror the text.)
Related
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…