Adding a custom CALayer to a view from "View Programming Guide for iOS"

Trying to work through Apple's "View Programming Guide for iOS" and in the section Embedding Layer Objects in a View I came up with this translation.

But with

myLayer = CGImage
I get an error "Cannot assign value of type 'CGImage' to type 'CALayer'" and with
let viewBounds = backingView.bounds
an error "Use of unresolved identifier 'backingView'"

I get that the guide is pretty old but what should I do to make this work the way it's supposed to? I would really appreciate any advice.


class ViewController: UIViewController {

  override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view.

  // Create the layer
  var myLayer = CALayer()

  // Set the contents of the layer to a fixed image. And set
  // the size of the layer to match the image size.
  let layerContents = UIImage(named: "myImage")
  let imageSize = layerContents?.size

  myLayer.bounds = CGRect(x: 0, y: 0, width: imageSize?.width ?? 0.0, height: imageSize?.height ?? 0.0)
  if let CGImage = layerContents?.cgImage {
  myLayer = CGImage // Error "Cannot assign value of type 'CGImage' to type 'CALayer'"
  }

  // Add the layer to the view.
  let viewLayer = view.layer
  viewLayer.addSublayer(myLayer)

  // Center the layer in the view.
  let viewBounds = backingView.bounds // Error "Use of unresolved identifier 'backingView'"
  myLayer.position = CGPoint(x: viewBounds.midX, y: viewBounds.midY)
  }
}


This is the actual code listing from the guide:

- (void)viewDidLoad {
  [super viewDidLoad];

  // Create the layer.
  CALayer* myLayer = [[CALayer alloc] init];

  // Set the contents of the layer to a fixed image. And set
  // the size of the layer to match the image size.
  UIImage layerContents = [[UIImage imageNamed:@"myImage"] retain];
  CGSize imageSize = layerContents.size;

  myLayer.bounds = CGRectMake(0, 0, imageSize.width, imageSize.height);
  myLayer = layerContents.CGImage;

  // Add the layer to the view.
  CALayer* viewLayer = self.view.layer;
  [viewLayer addSublayer:myLayer];

  // Center the layer in the view.
  CGRect viewBounds = backingView.bounds;
  myLayer.position = CGPointMake(CGRectGetMidX(viewBounds), CGRectGetMidY(viewBounds));

  // Release the layer, since it is retained by the view's layer
  [myLayer release];
}
Answered by ddownn in 412344022

seems I just needed to use

myLayer.contents = CGImage


and

let viewBounds = self.view.bounds
Accepted Answer

seems I just needed to use

myLayer.contents = CGImage


and

let viewBounds = self.view.bounds
Adding a custom CALayer to a view from "View Programming Guide for iOS"
 
 
Q