It is a way to input a multi-line string with SwiftUI. It is implemented using TextView of UIKit. I want Apple to release something like UITextView.
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 | |
struct ContentView: View { | |
@State var text: String = "" | |
var body: some View { | |
VStack { | |
Text(text) | |
.padding() | |
MultilineTextView(text: $text) | |
.padding() | |
.frame(width: 200, height: 100) | |
.border(Color.gray) | |
Spacer() | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
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 | |
struct MultilineTextView: UIViewRepresentable { | |
@Binding var text: String | |
final class Coordinator: NSObject, UITextViewDelegate { | |
private var textView: MultilineTextView | |
init(_ textView: MultilineTextView) { | |
self.textView = textView | |
} | |
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { | |
return true | |
} | |
func textViewDidChange(_ textView: UITextView) { | |
self.textView.text = textView.text | |
} | |
} | |
func makeCoordinator() -> Coordinator { | |
Coordinator(self) | |
} | |
func makeUIView(context: Context) -> UITextView { | |
let textView = UITextView() | |
textView.delegate = context.coordinator | |
textView.isScrollEnabled = true | |
textView.isEditable = true | |
textView.isUserInteractionEnabled = true | |
return textView | |
} | |
func updateUIView(_ uiView: UITextView, context: Context) { | |
uiView.text = text | |
} | |
} | |
struct MultilineTextView_Previews: PreviewProvider { | |
static var previews: some View { | |
PreviewWrapper() | |
} | |
struct PreviewWrapper: View { | |
@State var text: String = "" | |
var body: some View { | |
MultilineTextView(text: $text) | |
} | |
} | |
} |