Created
January 26, 2021 07:55
-
-
Save aaronlab/5e4e7df50f74b5fc66065c0d16386323 to your computer and use it in GitHub Desktop.
UIViewRepresentable with UITextView
This file contains hidden or 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
struct MyTextView: UIViewRepresentable { | |
@Binding var text: String | |
init(text: Binding<String>) { | |
self._text = text | |
} | |
func makeUIView(context: UIViewRepresentableContext<MyTextView>) -> UITextView { | |
let textView = UITextView(frame: .zero) | |
textView.font = .systemFont(ofSize: 16, weight: .medium) | |
textView.textColor = BStoreTheme.UIColors.store900 | |
textView.backgroundColor = .gray | |
textView.delegate = context.coordinator | |
return textView | |
} | |
func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<MyTextView>) { | |
uiView.text = self.text | |
} | |
// MARK: - COORDINATOR | |
func makeCoordinator() -> MyTextView.Coordinator { | |
return Coordinator(self) | |
} | |
class Coordinator: NSObject, UITextViewDelegate { | |
var parent: MyTextView | |
init(_ parent: MyTextView) { | |
self.parent = parent | |
} | |
// Update Text | |
func textViewDidChange(_ textView: UITextView) { | |
self.parent.text = textView.text | |
} | |
// Limit Text Count | |
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { | |
let currentCharacterCount = textView.text.count | |
if (range.length + range.location > currentCharacterCount) { | |
return false | |
} | |
let newLength = currentCharacterCount + text.count - range.length | |
return newLength <= 200 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment