Swift Sending Data from Child View to Parent View Controller

How to pass data to parent view controller

One strategy would be to set the parent as a delegate of the child. You would create this relationship in a prepare(for:sender:) function.

If you are unfamiliar with delegation, this article is a good guide: https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef

Swift - Pass data from Child View to Parent View

So as per the code you have done with declaration but not initialized the delegate. So go to you ParentView and assign the delegate in viewDidLoad or in the function where you prepare to move on child like:-

toChildView.delegate = self

And try again. :-)

How to pass data from child to parent view controller? in swift

You can use protocols/delegate

Here is a very very straightforward explanation, no bs:
https://www.youtube.com/watch?v=guSYMPaXLaw

Or in your situation you can also use NSNotificationCenter

You can do something like this:

The "sender" view controller would do

let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("printValue", object: nil, userInfo: ["value" : "Pass Me this string"])

The receiver view controller then can listen to the notification.

let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: #selector(printValue), name: "printValue", object: nil)

func printValue(notification:NSNotification) {
let userInfo:Dictionary<String,String> = notification.userInfo as! Dictionary<String,String>
let item = userInfo["value"]! as String

print(item,self)
}

How to pass data from parent view controller to child container view controller

You can try it more early like

let childVC = storyboard!.instantiateViewController(withIdentifier: "ChildVC") as! ChildVC
childVC.boolVariable = true

Swift - Pass data from parent view controller to child view controller

When you add a Container View in storyboard it adds a child view controller and a segue from the parent view controller to child view controller.

Sample Image

This segue is performed immediately after the parent view controller is loaded. Pass the data from EventDetails to InvitedController in prepare for segue method

class EventsMainController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EventDetails" {
if let eventDetails = segue.destination as? EventDetails {
eventDetails.eventId = "FromEventsMainController"
}
}
}
}
class EventDetails: UIViewController {
var eventId = String()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "InvitedController" {
if let invitedController = segue.destination as? InvitedController {
invitedController.eventId = self.eventId
}
}
}
}
class InvitedController: UIViewController {
var eventId = String()
override func viewDidLoad() {
super.viewDidLoad()
print(eventId)//FromEventsMainController
}
}

How to pass data from child to parent view controller? in swift

You can use protocols/delegate

Here is a very very straightforward explanation, no bs:
https://www.youtube.com/watch?v=guSYMPaXLaw

Or in your situation you can also use NSNotificationCenter

You can do something like this:

The "sender" view controller would do

let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("printValue", object: nil, userInfo: ["value" : "Pass Me this string"])

The receiver view controller then can listen to the notification.

let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: #selector(printValue), name: "printValue", object: nil)

func printValue(notification:NSNotification) {
let userInfo:Dictionary<String,String> = notification.userInfo as! Dictionary<String,String>
let item = userInfo["value"]! as String

print(item,self)
}

Swift sending data from child view to parent view controller

Delegation pattern is your friend.

Declare a protocol on your child view controller that the parent view controller will implement. Whenever you want, call a method on the delegate reference you are holding in the child view controller - this will update the parent view controller with data from child VC.

This SO question explains the child parent delegation neatly How do I set up a simple delegate to communicate between two view controllers?

How do I pass data from a child view to a parent view to another child view in SwiftUI?

You can use EnvironmentObject for stuff like this...

The nice thing about EnvironmentObject is that whenever and wherever you change one of it's variables, it will always make sure that every where that variable is used, it's updated.

Note: To get every variable to update, you have to make sure that you pass through the BindableObject class / EnvironmentObject on everyView you wish to have it updated in...

SourceRectBindings:

class SourceRectBindings: BindableObject {

/* PROTOCOL PROPERTIES */
var willChange = PassthroughSubject<Application, Never>()

/* Seems Like you missed the 'self' (send(self)) */
var sourceRect: CGRect = .zero { willSet { willChange.send(self) }
}

Parent:

struct ParentView: view {
@EnvironmentObject var sourceRectBindings: SourceRectBindings

var body: some View {
childViewA()
.environmentObject(sourceRectBindings)
childViewB()
.environmentObject(sourceRectBindings)
}
}

ChildViewA:

struct ChildViewA: view {
@EnvironmentObject var sourceRectBindings: SourceRectBindings

var body: some View {

// Update your frame and the environment...
// ...will update the variable everywhere it was used

self.sourceRectBindings.sourceRect = CGRect(x: 0, y: 0, width: 300, height: 400)
return Text("From ChildViewA : \(self.sourceRectBindings.sourceRect)")
}
}

ChildViewB:

struct ChildViewB: view {
@EnvironmentObject var sourceRectBindings: SourceRectBindings

var body: some View {
// This variable will always be up to date
return Text("From ChildViewB : \(self.sourceRectBindings.sourceRect)")
}
}

LAST STEPS TO MAKE IT WORK

• Go into your highest view you want the variable to update which is your parent view but i usually prefer my SceneDelegate ... so this is how i usually do it:

let sourceRectBindings = SourceRectBindings()

• Then in the same class 'SceneDelegate' is go to where i specify my root view and pass through my EnviromentObject

window.rootViewController = UIHostingController(
rootView: ContentView()
.environmentObject(sourceRectBindings)
)

• Then for the last step, I pass it through to may Parent view

struct ContentView : View {

@EnvironmentObject var sourceRectBindings: SourceRectBindings

var body: some View {
ParentView()
.environmentObject(sourceRectBindings)
}
}

If you run the code just like this, you'll see that your preview throws errors. Thats because it didn't get passed the environment variable.
To do so just start a dummy like instance of your environment:

#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(SourceRectBindings())
}
}
#endif

Now you can use that variable how ever you like and if you want to pass anything else other that the rect ... you can just add the variable to the EnvironmentObject class and you can access and update it



Related Topics



Leave a reply



Submit