Xcode makes it easy to create user interfaces by simply dragging items from the Object Library and placing it on a view of your storyboard. However, user interface objects often are designed to appear a certain way. For example, the switch object that lets users toggle between on and off, is meant to appear horizontally.
When users click on the switch, the switch slides left and right, but what if you want the switch to appear vertically so clicking on the switch slides it up and down?
Logically, you would think Xcode would offer a feature that would let you rotate a user interface object as easily as you might rotate an object in a graphics program like Photoshop or Illustrator. Unfortunately, this doesn’t seem to be the case so you need to rotate user interface objects using Swift code.
First, drag and drop your user interface object on a storyboard of your project. Then control-drag to create an IBOutlet. Now use the transform and CGAffineTransform commands to rotate a user interface item.
Suppose you created a switch on a storyboard that you want to rotate. In your Swift file (such as the ViewController.swift file), make sure you have an IBOutlet so you manipulate it using Swift code such as:
Now define the angle you want to rotate the object, declaring it as CGFloat. Oddly, if you want to rotate an object, -90 will actually be too far so you need to experiment with other values instead. To rotate a switch vertically, the angle must be specified as -89.55 as follows:
Now use the transform and CGAffineTransform commands to rotate the switch like this:
So if you create an iOS project and place a switch on the user interface, your complete code in the ViewController.swift file can look like this:
By using Swift code, you can rotate user interface objects on your user interface. You can download an example program below.