ios - 使用 NSUserDefaults 保存和格式化字符串

标签 ios swift nsuserdefaults

为了保存字符串,我使用以下代码:

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

要加载以前保存的字符串,我使用以下代码:

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

但是,该字符串不保留格式(color)!。是否可以使用 NSUserDefaults 保存字符串并对其进行格式化,还是我需要使用其他方法?

最佳答案

已找到解决方案。 例如在此处保存新文本

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

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

    textView.resignFirstResponder()
}

打开时上传保存的文本

override func viewDidLoad() {

    super.viewDidLoad()

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

    }

}

使用 NSAttributedString 而不是 NSMutableAttributedString!

关于ios - 使用 NSUserDefaults 保存和格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37258155/

相关文章:

ios - Metal 着色语言 IR 格式

ios - 使用 cocoa pod 在 iOS 中初始化 Fabric-Answer

ios - 将 iCloud 数据迁移到本地存储并阻止 iCloud 继续响应

iOS Swift Firestore 以及如何避免单例

ios - 具有嵌套队列的串行调度队列

ios - 具有多个 CollectionViewLayout 的单个 CollectionView。为什么布局困惑?

ios - 在应用程序终止之间保留 NSUserDefaults 信息

ios - 更改 View - (void)applicationWillEnterForeground :(UIApplication *)application

ios - 当我的应用程序在 iOS 上终止时,保存 NSUserDefaults 的正确方法是什么

ios - 无法在属性初始值设定项中使用实例成员,将变量设置为惰性不起作用