Search code examples
iosxcodeuiimageviewautolayoutstoryboard

Is it possible to rotate an image in Storyboard or do you have to do it programmatically?


Assume you have a triangle image you want to use at different angles (e.g., 180 degrees, 90 degrees).

Is it possible to rotate the triangle image within Storyboard, or do you need to do it programmatically?


Solution

  • You could probably create an IBDesignable & IBInspectable UIView subclass that had a rotation angle property, and applied a transform to the image it contained.

    IBInspectable allows you to expose custom properties of your custom views in IB's Attributes inspector.

    Making a view IBDesignable allows you to view a preview of your custom view object in IB.

    Edit:

    This is a very old thread, but I decided to implement a custom UIView that allows rotation, as I described. Since it's now 2021, I used Swift:

    @IBDesignable class RotatableView: UIView {
    
        @objc @IBInspectable var rotationDegrees: Float = 0 {
            didSet {
                print("Setting angle to \(rotationDegrees)")
                let angle = NSNumber(value: rotationDegrees / 180.0 * Float.pi)
                layer.setValue(angle, forKeyPath: "transform.rotation.z")
            }
        }
    }
    

    That yields the following in Interface Builder:

    enter image description here