gpt4 book ai didi

ios - 如何随着时间的推移永久保存文本行

转载 作者:行者123 更新时间:2023-11-30 11:07:09 25 4
gpt4 key购买 nike

每当我单击按钮时,我都希望将标签中的文本保存到 TextView 中,并且我也想保留 TextView 中已有的内容。这是到目前为止我的代码:

@IBOutlet weak var label: UILabel!
@IBOutlet weak var saved2: UITextView!

@IBAction func sve(_ sender: Any) {
let savedString = label.text
let userDefaults = Foundation.UserDefaults.standard
userDefaults.set(savedString, forKey: "key")
}

override func viewWillAppear(_ animated: Bool) {
let userDefaults = Foundation.UserDefaults.standard
let value = userDefaults.string(forKey: "key")
saved2.text = value
}

如何在不重置 TextView 的情况下将新值保存到下一行?

最佳答案

也许你想做这样的事情?

protocol TextStorage: class {
var text: String { get set }
}

final class TextStorageImpl: TextStorage {

private var storage = UserDefaults.standard
private let key = "key"

var text: String {
get {
return storage.string(forKey: key) ?? ""
}
set {
var newString = text
newString.append(newValue)
storage.set(newString, forKey: key)
}
}
}

final class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var saved2: UITextView!

private let textStorage: TextStorage = TextStorageImpl()

@IBAction func save(_ sender: Any) {
if let text = label.text {
textStorage.text = text
}
}

override func viewWillAppear(_ animated: Bool) {
saved2.text = textStorage.text
}
}

关于ios - 如何随着时间的推移永久保存文本行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52582268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com