I 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]