Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you rotate text for UIButton and UILabel in Swift?

How can you rotate text for UIButton and UILabel? 90 degrees, 180 degrees.

Note: Before you mark this as a duplicate, I am intentionally modelling my question as a Swift version of this one: How can you rotate text for UIButton and UILabel in Objective-C?

like image 346
Suragch Avatar asked Feb 25 '15 11:02

Suragch


People also ask

How do I rotate text in Swiftui?

Use any one of the . rotationEffect() methods to rotate any View clockwise, including Button and Text . Use the overloaded method with an anchor argument to rotate around a different point.


2 Answers

I am putting my answer in a similar format to this answer.

Here is the original label:

enter image description here

Rotate 90 degrees clockwise:

yourLabelName.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2) 

enter image description here

Rotate 180 degrees:

yourLabelName.transform = CGAffineTransform(rotationAngle: CGFloat.pi) 

enter image description here

Rotate 90 degrees counterclockwise:

yourLabelName.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2) 

enter image description here

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

  • How to do transforms on a CALayer?
  • How to apply multiple transforms in Swift
  • CTM transforms vs Affine Transforms in iOS (for translate, rotate, scale)
like image 66
Suragch Avatar answered Oct 04 '22 17:10

Suragch


If you do this a lot, you'll wan't to make an extension. Also this will allow you to rotate your view 0-360 degrees.

extension UIView {     func rotate(degrees: CGFloat) {         rotate(radians: CGFloat.pi * degrees / 180.0)     }      func rotate(radians: CGFloat) {         self.transform = CGAffineTransform(rotationAngle: radians)     } } 

Then you can simply call rotate on your views

myView.rotate(degrees: 90) 
like image 29
dsrees Avatar answered Oct 04 '22 17:10

dsrees