简体   繁体   中英

How to change Width in a UITextField with UIViewRepresentable in SwiftUI?

在此处输入图像描述 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]

  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM