Search code examples
swiftgetset

How to change variable value declared in a class from another class?


I have a 2 viewcontrollers, in vC1 a variable isShowListAsked : Bool = false is declared , on clicking map button it goes to vC2 . In vC2 there is a button named List. I want that : after clicking List button it go back to vC1 and vC1 variable value should changed to true. But it is still remains False.

Please help me .

Thanks in advance.

On clicking List button i am able to go back to vC1 but not able to set isShowListAsked = true . i tried get{} set {}.

In vC1 :

class vC1 : UIViewController
 {
var isShowListAsked : Bool = false

    var IsShowListAsked : Bool {
        get {
            return isShowListAsked
        }
        set{
            isShowListAsked = newValue
        }
    }
}

Then after clicking In vC2 :

class vC2 : UIViewController 
{
var vc = vC1()

 @IBAction func mapListSegmentTapped(_ sender: Any) {

       if mapListSegment.selectedSegmentIndex == 1 
     {
       vc.IsShowListAsked = true

        }
        if mapListSegment.selectedSegmentIndex == 0 
      {
            vc.IsShowListAsked = false
        }
   }
}

After going back i am checking variable value in viewWillappear()

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

      print(" isshowListAsked = \(IsShowListAsked) ") // print false
   }

Expected Result :

print(" isshowListAsked = \(IsShowListAsked) ") // print True

Actual Result :

print(" isshowListAsked = \(IsShowListAsked) ") // print false

Solution

  • Use Closures to solve your problem statement.

    Create a closure in VC2 of type ((Bool)->())? and call it with the relevant true/false values in mapListSegmentTapped(_:) method, i.e.

    class VC2: UIViewController {
        var handler: ((Bool)->())?
    
        @IBAction func mapListSegmentTapped(_ sender: Any) {
            if mapListSegment.selectedSegmentIndex == 1 {
                self.handler?(true)
            } else if mapListSegment.selectedSegmentIndex == 0 {
                self.handler?(false)
            }
        }
    }
    

    Now, set this closure when you're presenting the instance of VC2 from VC1 i.e.

    class VC1 : UIViewController {
        var isShowListAsked: Bool = false
    
        func onTapMapButton(_ sender: UIButton) {
            if let controller = self.storyboard?.instantiateViewController(withIdentifier: "VC2") as? VC2 {
                controller.handler = {[weak self] (value) in
                    self?.isShowListAsked = value
                    print(self?.isShowListAsked) 
                }
                self.present(controller, animated: true, completion: nil)
            }
        }
    }