0

To save a string, I use the following code:

defaults.setObject(textViews.text, forKey: "userNameKey")

To load a previously saved string, I use this code:

if let name = defaults.stringForKey("userNameKey") {
        textViews.text = name
}

However, the string does not preserve the formatting (color)!. Is it possible to save the string and format it using NSUserDefaults, or do I need to use some other method?

SashDing
  • 157
  • 1
  • 10
  • 2
    what is `textViews.text`? Is it a NSString? Or an attributed string? A NSString does not have any color information. – luk2302 May 16 '16 at 16:02
  • 1
    You are saving a `String` to the user defaults. Only an `NSAttributedString` contains color information. You'll have to find a way to store an `NSAttributedString` in user defaults. – Slayter May 16 '16 at 16:03
  • 4
    See http://stackoverflow.com/questions/36940275/how-to-use-store-and-use-an-nsmutableattributedstring-in-nsuserdefaults – rmaddy May 16 '16 at 16:07
  • Or you can save `NSDictionary` of text and RGB. – TheTiger May 16 '16 at 16:17
  • to rmaddy: This method preserves the format, but loses text – SashDing May 16 '16 at 16:54
  • @SashDing No, that method does not lose text. Please update your question with your actual relevant code showing how you save and restore the attributed text of your text view. Be sure your update includes log output showing before and after values. Note: When you wish to reply to someone, please use the `@` symbol before their username. – rmaddy May 16 '16 at 17:35
  • Thanks for all the important tips! – SashDing May 17 '16 at 09:06

1 Answers1

1

Solution found. Save the new text for example here

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let data = NSKeyedArchiver.archivedDataWithRootObject(textView.attributedText)
    NSUserDefaults.standardUserDefaults().setObject(data, forKey: "sawedString")

    textView.resignFirstResponder()
}

Upload saved text when opening

override func viewDidLoad() {

    super.viewDidLoad()

    if let myStringData = NSUserDefaults.standardUserDefaults().objectForKey("sawedString") as? NSData {
    let savedString = NSKeyedUnarchiver.unarchiveObjectWithData(myStringData) as? NSAttributedString
    textView.attributedText = savedString

    }

}

Use the NSAttributedString instead of the NSMutableAttributedString!

SashDing
  • 157
  • 1
  • 10