Swift/Xcode:APP重启后按钮状态无法保存的问题求助
Hey there! Let's work through this button state saving issue—totally get how annoying it is when something that feels straightforward doesn't stick after restarting your app, especially when you're just starting out with Swift and Xcode.
Based on what you've shared, here are the most common fixes to get your button's selected state to persist:
1. Make Sure You're Writing to UserDefaults When the Button Toggles
First, double-check that you're actually saving the button's state every time it's tapped. If you only set up the read part but forgot the write, the state will never be stored. Add this to your button's IBAction:
@IBAction func toggleButton(_ sender: UIButton) { // Toggle the button's selected state sender.isSelected.toggle() // Save the new state to UserDefaults UserDefaults.standard.set(sender.isSelected, forKey: "isTargetButtonSelected") // Optional: Force sync (modern iOS usually handles this automatically, but it's safe to add for testing) UserDefaults.standard.synchronize() }
Pro tip: Pick a clear, unique key name—avoid generic names like "buttonState" so you don't mix it up with other saved values later.
2. Restore the State When the View Loads
Next, you need to load the saved state when your view first appears. Add this to your view controller's viewDidLoad method (or viewWillAppear if your view comes and goes):
override func viewDidLoad() { super.viewDidLoad() // Fetch the saved state from UserDefaults; use false as the default if no value exists yet let savedButtonState = UserDefaults.standard.bool(forKey: "isTargetButtonSelected") // Apply the saved state to your button yourButtonOutlet.isSelected = savedButtonState }
Important: If you set an initial state in Interface Builder, this code will overwrite it with the saved value—exactly what you want! If you skip this step, the button will always revert to the IB-set state on restart.
3. Check for Typos in Your UserDefaults Key
This is a super common mistake! Make sure the key name you use to save (forKey:) is exactly the same as the one you use to read (bool(forKey:). A tiny typo like "isButtonSelected" vs "buttonIsSelected" will break the persistence.
4. Verify the State is Actually Saving
To debug, add a print statement right after saving to confirm the value is being stored correctly:
@IBAction func toggleButton(_ sender: UIButton) { sender.isSelected.toggle() UserDefaults.standard.set(sender.isSelected, forKey: "isTargetButtonSelected") // Test reading back immediately let savedValue = UserDefaults.standard.bool(forKey: "isTargetButtonSelected") print("Saved button state: \(savedValue)") }
If the print output matches the button's state when you tap it, the save is working. If restarting still resets the state, check that you're loading the state in the right place (make sure yourButtonOutlet is connected properly and you're not trying to set it before the view is loaded).
内容的提问来源于stack exchange,提问作者Medicine Man

