Search code examples
iosswiftxcodeuiswitch

How do i change the value of a UISwitch from a different class in swift Xcode?


Im creating an app and i need to change the value of a UISwitch from false to true once the user presses on the agree button.

So when the user clicks on a button there are presented with a page involving terms and conditions and on the page there are two buttons one is "Disagree" and the other is "Agree", when the user clicks on the agree button the page is dismissed which takes you back to the previous sign up form and needs to have changed the UISwitch from false to true and obviously when disagree is clicked the page is dismissed and the switch should remain on false

Here is the code that i am using and i am not sure why it doesnt work:

Is my SignUpVC class i have the following:

where i create my switch:

 let termsAndConditionsBox: UISwitch = {
    let switchA = UISwitch()
    return switchA
}()

i use this to change the value of the switch which works when i call the function in this class

func setAgreeSwitch(value: Bool) {
    termsAndConditionsBox.isOn = value
}

but when i call the above function the following way to change the switch value to true it doesnt work:

 @objc func handleAgreeTapped() {
    let signUpVC = SignUpVC()
    signUpVC.setAgreeSwitch(value: true)
}

TermsAConditions Tapped code:

@objc func TermsAndConditionsTapped() {
    let termsAndConditions = TermsAndConditionsVC()
    present(termsAndConditions, animated: true, completion: nil)
    
}

how do i make this work?


Solution

  • This

     let signUpVC = SignUpVC()
    

    is a new object not the presented 1 , you need a delegate inside TermsAConditionsVC

    weak var delegate:SignUpVC?
    

    Then

    @objc func handleAgreeTapped() {
       delegate?.setAgreeSwitch(value: true)
    }
    

    Also don't forget to set the delegate property when you navigate to TermsAConditionsVC

    termsAndConditions.delegate = self
    present(termsAndConditions, animated: true, completion: nil)