Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Last active May 3, 2024 15:12
Show Gist options
  • Save takoikatakotako/c9d351da76b084b1cc98f39dbfdeaf14 to your computer and use it in GitHub Desktop.
Save takoikatakotako/c9d351da76b084b1cc98f39dbfdeaf14 to your computer and use it in GitHub Desktop.
SwiftUI delegate sample
import SwiftUI
struct ContentView: View, MyProtocol {
@State var text: String = "My Text"
var body: some View {
NavigationView {
VStack {
Text(text)
NavigationLink(destination: SecondView(delegate: self)) {
Text("2nd View")
}
}
}
}
func myFunc() {
text = "Changed Text"
}
}
protocol MyProtocol {
func myFunc()
}
struct SecondView: View {
var delegate: MyProtocol
var body: some View {
Button(action: {
self.delegate.myFunc()
}) {
Text("ChangeText")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@nileshteji
Copy link

nileshteji commented Apr 19, 2024

Your Struct is non class type which cannot conform to a protocol , this will give you a compile time error
ContentView cannot conform to protocol

@takoikatakotako
Copy link
Author

@nileshteji
Hi.
Thank you for your comment.
In my environment, working well.
Please tell me your environment.
Thank you.

@takoikatakotako
Copy link
Author

swift --version
swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0

Xcode Version 15.3 (15E204a)

iPhone Simulator Version is 17.4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment