Oren Edrich
Oren Edrich

Reputation: 674

Save UIButton state

class GameViewController: UIViewController, UIPopoverPresentationControllerDelegate {

@IBOutlet weak var instructions: UIButton!

@IBAction func instructions(_ sender: AnyObject) {
    instructions.isHidden = true


}

This is my code to display instructions on how to use the app. I currently have an image-button and when I click on it the image disappears. This works great but I don't want the instructions to pop up overtime someone opens the app. I want to use "Userdefaults" to save the state of the button. I just recently updated to swift 3.0 and I can't find anyone who explains how to it, please help!

Upvotes: 0

Views: 574

Answers (2)

pedrouan
pedrouan

Reputation: 12910

UserDefaults is very helpful dictionary for storing some user defined preferences. It is already available from iOS version 2.0.

It is able to save Int, Bool, String, Array, Dictionary, Date and more.

Swift 3:

Setting:

// put this code right into the @IBAction methods of your UIButton event
let defaults = UserDefaults.standard
defaults.set(true, forKey: "InstructionsButtonIsHidden")

Retrievals:

// you may need to put these lines in your didFinishLaunching or viewDidLoad method 
let defaults = UserDefaults.standard
let isHidden = defaults.bool(forKey: "InstructionsButtonIsHidden")

Be aware not to save too much data as it could slow your app's launch.

Upvotes: 1

Yagnesh Dobariya
Yagnesh Dobariya

Reputation: 2251

UserDefaults.standard().set("True", forKey: "isHidden")

print("\(UserDefaults.standard.value(forKey: "isHidden")!)")

Upvotes: 0

Related Questions