1

enter image description hereI am new in IOS and working on the SwiftUI. I wrapped UITextField in the SwiftUI using UIViewRepresentable. But the issue is:

I am unable to fix the wrapped UITextField width and height. The text writes only in one line and increases the width of the UITextfield when writing more text.

Here is my code:

struct SecondWrappedTextField: UIViewRepresentable {
    @Binding var text: String // Declare a binding value

    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.delegate = context.coordinator
        textField.textAlignment = .left
        textField.contentVerticalAlignment = .top
        return textField
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text // 1. Read the binded
        print("Selcted Text")
        let getSelectedText=UserDefaults.standard.string(forKey: text) ?? ""
        let mainString = text
        let stringToColor = getSelectedText
        let range = (mainString as NSString).range(of: stringToColor)

        let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
        mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)

        
        uiView.attributedText = mutableAttributedString
    }

    func makeCoordinator() -> Coordinator {
        
        return Coordinator(text: $text)
    }

    class Coordinator: NSObject, UITextFieldDelegate,ObservableObject {
        @Binding var text: String
        init(text: Binding<String>) {
            self._text = text
            
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            DispatchQueue.main.async {
                self.text = textField.text ?? "" // 2. Write to the binded
                let abc = textField // 2. Write to the binded
                print("TEXT")
                print(self.text)
                
              }
        }
    }
    
    
}


SecondWrappedTextField(text: $textNote).multilineTextAlignment(.leading).background(Color.white).frame(width:200,height:200)

Sorry for the bad English.[Image]

zeytin
  • 5,545
  • 4
  • 14
  • 38
Muhammad Farooq
  • 263
  • 3
  • 10

1 Answers1

0
  • UITextField : For entering a single line of text. Use secure entry for sensitive data such as passwords.
  • UITextView : For displaying or entering one or more lines of text.

So if you want to have multiline editable text field, you should use UITextView as UIViewRepresentable.

This is an example tutorial by Prafulla Singh, it works amazingly in my project. https://betterprogramming.pub/swiftui-multiline-content-fit-textfield-3abbdcedaabc

Yoyo
  • 21
  • 2