Skip to content

Input a multi-line string with SwiftUI

   

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.

MultilineTextView

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()
}
}
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)
}
}
}

  1. Create a sequential numbered array in Swift
  2. Show picker from bottom with SwiftUI
  3. Using UIImagePickerController with SwiftUI
  4. Do not change the color of the Image in the Button with SwiftUI
  5. I tried all the ModalPresentationStyle of iOS 13
  6. Detect video end with Swift
  7. Play videos with Swift