Created
June 18, 2018 13:01
-
-
Save yajamon/f7b97d278d9ef4e6fa1fb6a21b104182 to your computer and use it in GitHub Desktop.
This UITextField is save to UserDefaults when editingDidEnd, can restore text from UserDefaults, and can edit key in Inspector of Interface-Builder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class RestorableTextField: UITextField { | |
@IBInspectable var defaultsKey: String = "" | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
self.addTarget(self, action: #selector(saveToUserDefaults(_:)), for: .editingDidEnd) | |
} | |
@objc func saveToUserDefaults(_ sender:RestorableTextField) { | |
guard defaultsKey != "" else { return } | |
UserDefaults.standard.set(sender.text ?? "", forKey: defaultsKey) | |
// this method is unnecessary and shouldn't be used. | |
// UserDefaults.standard.synchronize() | |
} | |
func restoreByUserDefaults() { | |
guard defaultsKey != "" else { return } | |
guard let text = UserDefaults.standard.string(forKey: defaultsKey) else { return } | |
guard text != "" else { return } | |
self.text = text | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 4.