article

Sunday, November 21, 2021

SwiftUI Multiline TextField

SwiftUI Multiline TextField

ContentView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
//  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<multilinetextfield>) -> 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<multilinetextfield>) {
        
  }
    
  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
      }
  }
}
</multilinetextfield></multilinetextfield>

Related Post