Samarey
Samarey

Reputation: 722

View Controller value passing

I have an iOS application that has Controller A, which uses a tableview that adopts the 3D touch protocol. Each cell actually adopts this 3D touch so when selecting a cell, it will bring a modal view controller (Controller B).

This controller B is basically used to fill information that is then added to the tableview on Controller A.

So in applying the DRY principle, I am reusing Controller B for adding and editing data.

Problem:

Controller B has a property

var didPresentVia3dTouch : Bool = false

and a method:

public func setPreference(editMode: Bool) {
   self.didPresentVia3dTouch = editMode
}

So this method is supposed to set the value of didPresentVia3dTouch to true from false when the tablecell in Controller A is forced touch, rather than being presented thru the navigation item button as a general 'Add' call.

in Controller A, i've kept a reference to Controller B like so:

var controllerBref = AddEditViewController()

so in the method

func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController)

I call the method setPreference from Controller B like so:

controllerBRef.setPreference(true)

in order to invoke Controller B to act as an Edit view for data on that cell.

One issue that i've noticed is that when I print the value of Controller B's method setPreference(editMode: Bool), the editMode constant, it prints out true, but in the viewWillAppear, viewDidAppear, viewDidLoad, and all other methods, the value for didPresentVia3dTouch still reads false, so therefore not allowing me to change the title of the navigation bar whether its on Edit mode or Add new mode.

Is there something I am missing or not understanding here? I tried delegation but could not figure it out.

Upvotes: 0

Views: 53

Answers (2)

Paulw11
Paulw11

Reputation: 114828

You need to set the property on the view controller instance that will be presented, not some random instance that you have instantiated and stored in a property.

Use:

func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
    if let destVC = viewControllerToCommit as? AddEditViewController {
        destVC.setPreference(editMode:true)
    }
}

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

The problem is that this line

var controllerBref = AddEditViewController()

has no relation the currently presented VC , i mean it's a separate instance , so when you present B set it to controllerBref

Upvotes: 0

Related Questions