Skip to content

Using Cosmos with SwiftUI

Evgenii Neumerzhitckii edited this page Jul 11, 2020 · 5 revisions

This is an example of how to show Cosmos view using SwiftUI.

import SwiftUI
import Cosmos

// A SwiftUI wrapper for Cosmos view
struct MyCosmosView: UIViewRepresentable {
    @Binding var rating: Double

    func makeUIView(context: Context) -> CosmosView {
        CosmosView()
    }

    func updateUIView(_ uiView: CosmosView, context: Context) {
        uiView.rating = rating
    
        // Autoresize Cosmos view according to it intrinsic size
        uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
        uiView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
      
        // Change Cosmos view settings here
        uiView.settings.starSize = 40
    }
}

struct ContentView: View {
    @State var rating = 3.0
  
    var body: some View {
        MyCosmosView(rating: $rating)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Clone this wiki locally