article

Sunday, November 21, 2021

SwiftUI Multiline TextField

SwiftUI Multiline TextField

ContentView.swift
//
//  ContentView.swift
//  Swiftuitest
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var txt = ""
    
    var body: some View {
        VStack{
            HStack{
                Button(action: {
                   
                }) {
                    Text("Cancel")
                }
                 
                Spacer()
                 
                Button(action: {

                }) {
                    Text("Submit").padding()
                }.background(Color.orange)
                .foregroundColor(.white)
                .clipShape(Capsule())
            }
            multilineTextField(txt: $txt)
                .background(Color.orange)
                .cornerRadius(10)
        }.padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct multilineTextField : UIViewRepresentable {
   
   
  @Binding var txt : String
   
  func makeCoordinator() -> multilineTextField.Coordinator {
      return multilineTextField.Coordinator(parent1 : self)
  }
  func makeUIView(context: UIViewRepresentableContext) -> UITextView {
      let text = UITextView()
      text.isEditable = true
      text.isUserInteractionEnabled = true
      text.text = "Type Something"
      text.textColor = .white
      text.font = .systemFont(ofSize: 20)
      text.delegate = context.coordinator
      text.backgroundColor = .clear
      return text
  }
   
  func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext) {
       
  }
   
  class Coordinator : NSObject,UITextViewDelegate{
      var parent : multilineTextField
      init(parent1 : multilineTextField) {
          parent = parent1
      }
      func textViewDidBeginEditing(_ textView: UITextView) {
          textView.text = ""
          textView.textColor = .black
      }
      func textViewDidChange(_ textView: UITextView) {
          self.parent.txt = textView.text
      }
  }
}

Related Post