如何在SwiftUI中使用UIViewRepresentable更改UITextField中的宽度?

时间:2020-10-31 14:27:28

标签: ios xcode swiftui uikit uitextfield

enter image description here我是IOS的新手,正在使用SwiftUI。我使用UIViewRepresentable将UITextField包装在SwiftUI中。但是问题是:

我无法修复包装的UITextField的宽度和高度。文本仅写成一行,并且在写入更多文本时会增加UITextfield的宽度。

这是我的代码:

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)

对不起,英语不好。[图片]

0 个答案:

没有答案