Last active
May 4, 2020 18:59
SwiftUIDocumentationUIViewRepresentable
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 SwiftUI | |
final class DataModel: ObservableObject { | |
static let shared = DataModel() | |
@Published var text = String() { | |
didSet { | |
UserDefaults.standard.set(text, forKey: "text") | |
} | |
} | |
} | |
struct ContentView : View { | |
var body: some View { | |
MultiTextView() | |
.padding() | |
} | |
} | |
struct MultiTextView: UIViewRepresentable { | |
@ObservedObject var data = DataModel.shared | |
func makeUIView(context: Context) -> UITextView { | |
let view = UITextView() | |
view.isScrollEnabled = true | |
view.isEditable = true | |
view.isUserInteractionEnabled = true | |
view.textAlignment = .left | |
view.delegate = context.coordinator | |
view.font = UIFont.systemFont(ofSize: 18) | |
if let loadedText = UserDefaults.standard.string(forKey: "text") { | |
view.text = loadedText | |
} | |
else { | |
view.text = "Start typing here" | |
} | |
return view | |
} | |
func updateUIView(_ uiView: UITextView, context: Context) { | |
view.text = data.text | |
} | |
func makeCoordinator() -> MultiTextView.Coordinator { | |
Coordinator(self) | |
} | |
class Coordinator: NSObject, UITextViewDelegate { | |
var control: MultiTextView | |
init(_ control: MultiTextView) { | |
self.control = control | |
} | |
func textViewDidChange(_ textView: UITextView) { | |
control.data.text = textView.text | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment