每当我单击一个按钮时,我都希望将标签中的文本保存到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的情况下将新值保存到下一行?
答案 0 :(得分:0)
也许您想做这样的事情?
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
}
}