Skip to content

Instantly share code, notes, and snippets.

@corysimmons
Forked from andrew-levy/SwiftUIViewModule.swift
Created October 24, 2023 19:24
Show Gist options
  • Save corysimmons/07c5fd7f2be2840ec3ca607d0d57cd11 to your computer and use it in GitHub Desktop.
Save corysimmons/07c5fd7f2be2840ec3ca607d0d57cd11 to your computer and use it in GitHub Desktop.
import ExpoModulesCore
import UIKit
import SwiftUI
import React
class SwiftuiView: ExpoView {
var name = "" {
didSet {
updateView(withName: name, withOptions: options)
}
}
var options: [String] = [] {
didSet {
updateView(withName: name, withOptions: options)
}
}
let hostingController = UIHostingController(rootView: MySwiftUIView())
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
addSubview(hostingController.view)
NSLayoutConstraint.activate([
hostingController.view.topAnchor.constraint(equalTo: self.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: self.bottomAnchor),
hostingController.view.leftAnchor.constraint(equalTo: self.leftAnchor),
hostingController.view.rightAnchor.constraint(equalTo: self.rightAnchor)
])
}
// Update the hosting controller's root view with updated prop values
func updateView(withName name: String, withOptions options: [String]) {
hostingController.rootView = MySwiftUIView(name: name, options: options)
}
}
struct MySwiftUIView: View {
var name = ""
var options: [String] = []
@State var isOpen = false
@State var picker = 0
@State var slider = 50.0
@State var isScaled = false
var body: some View {
NavigationView {
if #available(iOS 14.0, *) {
ScrollView {
VStack(spacing: 20) {
Text("SwiftUI + Expo!")
.font(.largeTitle)
.scaleEffect(isScaled ? 1.5 : 1.0)
.foregroundColor(isScaled ? .purple : .black)
Button("Animations work too!") {
withAnimation {
isScaled.toggle()
}
}
NavigationLink("To Details") {
Text("Details")
}
Picker("Picker", selection: $picker, content: {
ForEach(Array(options.enumerated()), id: \.1) { index, option in
Text(option)
.tag(index)
}
}).pickerStyle(.segmented)
if #available(iOS 16.0, *) {
Button("Toggle Sheet") {
isOpen.toggle()
}.sheet(isPresented: $isOpen) {
Text("Sheet content")
.presentationDetents([.medium, .large])
}.padding(.bottom, 100)
}
}
}.navigationTitle(Text("Home"))
}
}
}
}
import ExpoModulesCore
import SwiftUI
public class SwiftuiViewModule: Module {
public func definition() -> ModuleDefinition {
Name("SwiftuiForm")
View(SwiftuiView.self) {
Prop("name") { (view, name: String) in
view.name = name
}
Prop("options") { (view, options: [String]) in
view.options = options
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment