Dhruv
Dhruv

Reputation: 13

Save checkbox button state using userdefaults in swift

view controller had two check boxes buttons 1.chekcIn 2.checkOut

am saving the checkIN [ checkbox button] status in user defaults, working fine but when am using that userdefaults key in Nextviewcontroller its always showing true and not running into false block this is the code

inHomeview controller

@IBAction func CheckInButtonClick(_ sender: UIButton) {


        for senderdata in checkINOUT {
            senderdata.setImage( UIImage(named:"uncheck1"), for: .normal)
            print("uncheck is called")

        }


        sender.setImage(UIImage(named:"check1"), for: .normal)
         prefs.set(true, forKey: "check")
    prefs.synchronize()

    }

nextviewcontroller

   override func viewDidLoad() {
        super.viewDidLoad()
{        

 let prefs:UserDefaults = UserDefaults.standard
  if  prefs.bool(forKey: "check") ==true
        {
        print("select")

        } else {

            print("unselect")
        }

 }     

check box select its execute main block if unselect execute else block

how to over come this problem where I did mistake

Upvotes: 0

Views: 980

Answers (2)

Rashwan L
Rashwan L

Reputation: 38833

You´re not setting your userDefault value to false. You´re only setting it to true, that´s why it´s always true. And btw no need to use synchronize() Change your code to the following instead:

HomeViewController:

@IBAction func CheckInButtonClick(_ sender: UIButton) {
    for senderdata in checkINOUT {
        senderdata.setImage( UIImage(named:"uncheck1"), for: .normal)
        print("uncheck is called")
    }
    sender.setImage(UIImage(named:"check1"), for: .normal)
    UserDefaults.standard.set(true, forKey: "check")
}

NextViewController:

override func viewDidLoad() {
    super.viewDidLoad()       

    if UserDefaults.standard.bool(forKey: "check") {
        print("select")
    } else {
        print("unselect") {
    }
}

So do check where you want to set your check value to false and use it.

Update:
Just do this check:

if UserDefaults.standard.set(true, forKey: "check") {
    // Show data
} else {
    // segue to another viewController
}

Upvotes: 1

LNT
LNT

Reputation: 124

When you set "check" value as true once, it will always true, until you set "check" value to false. I think you should add some code to set "check" to false, when user not select the checkbox.

Upvotes: 0

Related Questions