Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CALayer equivalent in SwiftUI

Tags:

ios

ios13

swiftui

UIViews are known to be layer backed, but not sure about SwiftUI View. Is there a concept of layer in SwiftUI which can be added as sublayer, animated, everything you could do with CALayer?

like image 914
Deepak Sharma Avatar asked Jun 06 '19 07:06

Deepak Sharma


People also ask

What is CALayer in Swift?

An object that manages image-based content and allows you to perform animations on that content.

How do you make a CALayer?

You can create a new CALayer very easily with the following line of code: CALayer *sublayer = [CALayer layer]; Once you have a CALayer, you can set any properties on it you'd like. But remember there's one property you definitely have to set: it's frame (or bounds/position).

What is a view in Swift?

Views are the fundamental building blocks of your app's user interface, and the UIView class defines the behaviors that are common to all views. A view object renders content within its bounds rectangle, and handles any interactions with that content.


2 Answers

In the "Building Custom Views with SwiftUI" talk, they demonstrated that Views and Drawing models/interfaces have essentially been combined under the hood in the framework. Therefore, a View has layer like attributes but built onto the View itself rather than a layer abstraction.

Source: https://developer.apple.com/videos/play/wwdc2019/237/

like image 54
user3338275 Avatar answered Oct 23 '22 03:10

user3338275


import SwiftUI
import AVFoundation

struct DrawingView: UIViewRepresentable {

    private let view = UIView()

    var layer: CALayer? {
        view.layer
    }

    func makeUIView(context: Context) -> UIView {
        view
    }

    func updateUIView(_ uiView: UIView, context: Context) { }
}
like image 41
Mike Glukhov Avatar answered Oct 23 '22 02:10

Mike Glukhov