Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

swift - Is it possible to serialize a SwiftUI view (i.e. not the ViewModel/state info, but the actual view itself)?

Does Apple provide any way to serialize/deserialize a SwiftUI view for persistence reasons? To be clear, I mean the views themselves, not the data used to build them. I know Apple doesn't give us access to the view tree/hierarchy itself, which makes sense because they aren't 'objects' in a hierarchy, but there are view types, each with state, so I'm wondering if that can somehow be captured/persisted then recreated.

I'm asking because we're trying to mirror/mimic a similar concept in Windows WPF applications where you can serialize/deserialize entire UI elements into what's known as XAML, or Extensible Application Markup Language which is an XML format. You can store that data in say, a database, then reload it at runtime, rehydrating an entire UI, including bindings to data. While we don't need anything that elaborate--we just need loading static views--I'm not finding anything on this topic.

Now I know I could write my own 'builder' classes that look for types that I define from known 'model' types, then dynamically build up those views accordingly, but that would require writing an entire engine just for that limited purpose. So... is there any such thing already out there, or is this just not possible by design?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes! You can serialize a SwiftUI view. Just conform to the Codable protocol and you are good to go. Here is a small example:

import UIKit
import PlaygroundSupport
import SwiftUI

struct ContentView: View, Codable {
    var body: some View {
        VStack {
            Text("Hello World")
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())


let data = try? JSONEncoder().encode(ContentView())
print(data)

let contentView = try? JSONDecoder().decode(ContentView.self, from: data!)
print(contentView)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...