0

I have stetted up switch in my First View Controller and assigned the following action to it :-

class ThirdViewController: UIViewController {

@IBOutlet weak var Image: UIImageView!

@IBOutlet weak var playerNum1Button: UIButton!
  
@IBOutlet weak var toggleSwitch: UISwitch!
 
override func viewDidLoad() {
    super.viewDidLoad()

      self.toggleSwitch.setOn(UserDefaults.standard.bool(forKey: "toggleState"), animated: true)

}

@IBAction func numPlayers1(_ sender: Any) {
    
    performSegue(withIdentifier: "3to8segue", sender: self)
}
IBAction func toggleSwitch(_ sender: UISwitch) {
    
    if (toggleSwitch.isOn == true) {
        
        Image.image = UIImage(named: "Night")
        
    }
    else {
        
        Image.image = UIImage(named: "background")
        
    }
    
    UserDefaults.standard.set(sender.isOn, forKey: "toggleState")
    
}

It is Able to change the image in the First View Controller. But, how can I get that switch to change the image in 2nd View controller as well when it is turned on? Thanks for the help!

Pressing_Keys_24_7
  • 1,755
  • 2
  • 7
  • 33
  • 1
    Send the image name to the second view controller. Does this answer your question? [Passing Data between View Controllers](https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – Joakim Danielson Jul 23 '20 at 08:50
  • @JoakimDanielson I have looked on that solution before, but it's using sugues to transfer data. I want to change the image in the 2nd view controller by the click of a button in 1st View Controller – Pressing_Keys_24_7 Jul 23 '20 at 08:52
  • 1
    If you want to trigger an action then use delegate pattern or observer pattern but are really both view controllers active at the same time? – Joakim Danielson Jul 23 '20 at 08:56
  • 1
    @JoakimDanielson I guess I found the way. I am gonna use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} function to set the image on another view controller using delegates. – Pressing_Keys_24_7 Jul 23 '20 at 08:57
  • @Pressing_Keys_24_7, You got your output if yes it's okay else you can use protocol-delegate. – Ashutosh Mishra Jul 23 '20 at 09:04

1 Answers1

1

Using Notification Center

Example: In FirstViewController:

@IBAction func onPressButton(_ sender: UIButton) {
     UserDefaults.standard.set(sender.isSelected, forKey: "pressedButton")
     NotificationCenter.default.post(name: "changeImageBackground", object: nil)
}

In SecondViewController:

NotificationCenter.default.addObserver(target: self, selector: #selector(didChangeImageBackground), name: "changeImageBackground", object: nil)

@objc func didChangeImageBackground() {
    let changed = UserDefaults.standard.bool(forKey: "pressedButton")
    if changed {
    // image when pressed
    } else {
    // image when haven't pressed
    }
}
HHumorous
  • 174
  • 1
  • 11