Search code examples
swiftrotationcgaffinetransformswift-playground

Why won't Swift Playgrounds show a view's transform?


For example, this code just shows a rectangle unrotated in a Playground

let view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 150))
view.backgroundColor = UIColor.blue
view.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI / 3))

enter image description here

When it should look like this:

enter image description here


Solution

  • The playground is giving you a preview of the view, not rendering it within another view. The transform property only affects the presentation layer of the view and not its actual bounds. If you want to see the transform add your transformed view to the playgrounds live view and look in the assistant editor on the right.

    import PlaygroundSupport
    import UIKit
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 150))
    view.backgroundColor = UIColor.blue
    view.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI / 3))
    let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
    rootView.addSubview(view)
    PlaygroundPage.current.liveView = rootView