Last active
May 17, 2024 23:01
-
-
Save iOSappssolutions/5004629405a82a6eb079a74a1d88dbb8 to your computer and use it in GitHub Desktop.
coordinator.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// CoordinatorTest | |
// | |
// Created by Miroslav Djukic on 18.5.24.. | |
// | |
import SwiftUI | |
struct LabelView: UIViewRepresentable { | |
@Binding var text: String | |
class Coordinator: NSObject { | |
var parent: LabelView | |
init(parent: LabelView) { | |
self.parent = parent | |
} | |
func updateLabelText(_ newText: String) { | |
parent.text = newText | |
} | |
} | |
func makeUIView(context: Context) -> UILabel { | |
let label = UILabel() | |
return label | |
} | |
func updateUIView(_ uiView: UILabel, context: Context) { | |
uiView.text = text | |
} | |
func makeCoordinator() -> Coordinator { | |
return Coordinator(parent: self) | |
} | |
} | |
struct ContentView: View { | |
@State private var text = "Hello, SwiftUI!" | |
private var coordinator: LabelView.Coordinator? { | |
let labelView = LabelView(text: $text) | |
return labelView.makeCoordinator() | |
} | |
var body: some View { | |
VStack { | |
LabelView(text: $text) | |
.onAppear { | |
if let coordinator = self.coordinator { | |
coordinator.updateLabelText("Updated text from SwiftUI") | |
} | |
} | |
Button("Update Text") { | |
if let coordinator = self.coordinator { | |
coordinator.updateLabelText("Updated text \(Int.random(in: 0...1000))") | |
} | |
} | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment